关于C#:我们为什么要转换malloc的返回值?

Why do we cast return value of malloc?

本问题已经有最佳答案,请猛点这里访问。

有人能给我解释一下为什么有些程序员在malloc前面使用(char*)。我知道它会返回void,但是为什么我要它只返回char内存呢?对不起,我只是个编程新手。谢谢你


不需要强制转换EDOCX1的返回值(0),因为它的返回类型是void*

Can someone explain why do some programmers use (*char) in front of the malloc?

他们做错事(最有可能)通过铸造它(在良好的程序员看来)。

正如维基所说:

malloc返回一个空指针(void *),表示它是指向未知数据类型区域的指针。由于强大的类型系统,在C++中需要使用铸造,而在C<1>/Sub中则不是这样。缺少从malloc返回的特定指针类型是一些程序员所说的类型不安全行为:malloc是基于字节计数而不是基于类型分配的。这与C++返回了一个指针,它的类型依赖于操作数的C++ EDCOX1 6Ω操作符不同。可以将此指针"强制转换"到特定类型:

1
2
3
4
int *ptr;
ptr = malloc(10 * sizeof (*ptr));               /* without a cast */
ptr = (int *)malloc(10 * sizeof (*ptr));        /* with a cast */
ptr = reinterpret_cast<int *>(malloc(10 * sizeof (*ptr))); /* with a cast, for C++ */

这样的演员表演有其优点和缺点。

铸造的优点:

  • Including the cast allows a program or function to compile as C++.
  • The cast allows for pre-1989 versions of malloc that originally returned a char *.
  • Casting can help the developer identify inconsistencies in type sizing should the destination pointer type change, particularly if the pointer is declared far from the malloc() call.

铸造的缺点:

  • Under the ANSI C standard, the cast is redundant.
  • Adding the cast may mask failure to include the header stdlib.h, in which the prototype for malloc is found. In the absence of a prototype for malloc, the standard requires that the C compiler assume malloc returns an int. If there is no cast, a warning is issued when this integer is assigned to the pointer; however, with the cast, this warning is not produced, hiding a bug. On certain architectures and data models (such as LP64 on 64-bit systems, where long and pointers are 64-bit and int is 32-bit), this error can actually result in undefined behavior, as the implicitly declared malloc returns a 32-bit value whereas the actually defined function returns a 64-bit value. Depending on calling conventions and memory layout, this may result in stack smashing. This issue is less likely to go unnoticed in modern compilers, as they uniformly produce warnings that an undeclared function has been used, so a warning will still appear. For example, GCC's default behavior is to show a warning that reads"incompatible implicit declaration of built-in function" regardless of whether the cast is present or not.
  • If the type of the pointer is changed, one must fix all code lines where malloc was called and cast (unless it was cast to a typedef).

>1。重点是我的。


由于malloc的返回类型为void*,因此当您将结果赋给指针时,它将隐式转换为新类型。所以,没有必要进行明确的铸造。实际上,不鼓励使用显式强制转换,如本文所述。


malloc返回void*,它是一个通用指针,可以指向任何类型的数据。(char*)是一个显式类型转换,将malloc返回的指针从一个指针转换为任何对象,再转换为一个指向char的指针。这在C中是不必要的,因为它是隐式完成的,实际上建议不要这样做,因为它可以隐藏一些错误。

如果您需要将代码编译为C++,而不仅仅是C,那么您将需要显式转换,因为C++不执行隐式转换。


malloc()返回void*,因为malloc()不知道调用方将如何使用它在堆上分配的内存。因此,由调用方将(void*)转换成您想要在内存中使用的适当类型的指针。(int*)存储整数。存储字符等。

这么说之后,您不必显式地强制执行malloc()调用的返回。在某些情况下,这样做可能会导致错误。

请在这里读一下这个问题

铸造malloc的返回值有什么问题?

具体来说,什么是危险的铸造马尔洛克的结果?