Why do we cast return value of malloc?
有人能给我解释一下为什么有些程序员在malloc前面使用(char*)。我知道它会返回void,但是为什么我要它只返回char内存呢?对不起,我只是个编程新手。谢谢你
不需要强制转换EDOCX1的返回值(0),因为它的返回类型是
Can someone explain why do some programmers use (*char) in front of the malloc?
他们做错事(最有可能)通过铸造它(在良好的程序员看来)。
正如维基所说:
1 2 3 4 |
这样的演员表演有其优点和缺点。
铸造的优点:
- Including the cast allows a program or function to compile as C++.
- The cast allows for pre-1989 versions of
malloc that originally returned achar * .- 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 formalloc is found. In the absence of a prototype formalloc , the standard requires that the C compiler assumemalloc 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 declaredmalloc 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 atypedef ).
>1。重点是我的。
由于malloc的返回类型为void*,因此当您将结果赋给指针时,它将隐式转换为新类型。所以,没有必要进行明确的铸造。实际上,不鼓励使用显式强制转换,如本文所述。
malloc返回void*,它是一个通用指针,可以指向任何类型的数据。(char*)是一个显式类型转换,将malloc返回的指针从一个指针转换为任何对象,再转换为一个指向char的指针。这在C中是不必要的,因为它是隐式完成的,实际上建议不要这样做,因为它可以隐藏一些错误。
如果您需要将代码编译为C++,而不仅仅是C,那么您将需要显式转换,因为C++不执行隐式转换。
这么说之后,您不必显式地强制执行
请在这里读一下这个问题
铸造malloc的返回值有什么问题?
具体来说,什么是危险的铸造马尔洛克的结果?