C语言 为什么我们要转换 malloc 的返回值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20094394/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 10:21:57  来源:igfitidea点击:

Why do we cast return value of malloc?

cmalloc

提问by user3012799

Could someone explain to me why do some programmers use (char*) in front of the malloc? I know that it returns void but why do I want it to return just char memory? I'm sorry, I'm just a newbie in programming. Thank you

有人可以向我解释为什么有些程序员在 malloc 前面使用 (char*) 吗?我知道它返回 void 但为什么我希望它只返回 char 内存?对不起,我只是一个编程新手。谢谢

回答by haccks

No need to cast return value of mallocas its return type is void*.

不需要转换返回值,malloc因为它的返回类型是void*

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

有人能解释一下为什么有些程序员会(char *)在malloc前面使用吗?

They are doing wrong (most probably) by casting it (in good programmers opinion).

他们通过转换(在好的程序员看来)做错了(很可能)。

As wikisays:

正如维基所说:

mallocreturns a void pointer (void *), which indicates that it is a pointer to a region of unknown data type. The use of casting is required in C++ due to the strong type system, whereas this is not the case in C1. The lack of a specific pointer type returned from mallocis type-unsafe behavior according to some programmers: mallocallocates based on byte count but not on type. This is different from the C++ newoperatorthat returns a pointer whose type relies on the operand. One may "cast" this pointer to a specific type:

malloc返回一个空指针 ( void *),表示它是一个指向未知数据类型区域的指针。由于强类型系统,在 C++ 中需要使用强制转换,而在 C 1 中则不是这种情况malloc根据一些程序员的说法,缺少返回的特定指针类型是类型不安全的行为:malloc基于字节数而不是类型进行分配。这与返回类型依赖于操作数的指针的 C++new运算符不同。可以将此指针“强制转换”为特定类型:

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++ */

There are advantages and disadvantages to performing such a cast.

执行这样的演员表有优点也有缺点

Advantages to casting:

铸造优势:

  • Including the cast allows a program or function to compile as C++.
  • The cast allows for pre-1989 versions of mallocthat 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.
  • 包括强制转换允许程序或函数编译为 C++
  • 演员表允许malloc最初返回的1989 年之前的版本char *
  • 如果目标指针类型发生变化,转换可以帮助开发人员识别类型大小的不一致,特别是当指针声明远离malloc()调用时。

Disadvantages to casting:

铸造的缺点:

  • 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 mallocis found. In the absence of a prototype for malloc, the standard requires that the C compiler assume mallocreturns 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 mallocreturns 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 mallocwas called and cast (unless it was cast to a typedef).
  • 在 ANSI C 标准下,强制转换是多余的
  • 添加强制转换可能会掩盖包含头文件的失败,在头文件stdlib.hmalloc找到了 的原型。在没有原型的情况下malloc,标准要求 C 编译器假定malloc返回一个 int。如果没有强制转换,则将此整数分配给指针时发出警告;然而,使用演员表,不会产生这个警告,隐藏了一个错误。在某些架构和数据模型上(例如 64 位系统上的 LP64,其中 long 和指针是 64 位,int 是 32 位),这个错误实际上可能导致未定义的行为,因为隐式声明malloc返回 32 位值,而实际定义的函数返回 64 位值。根据调用约定和内存布局,这可能会导致堆栈粉碎。这个问题在现代编译器中不太可能被忽视,因为它们一致地产生警告,表明使用了未声明的函数,因此警告仍然会出现。例如,GCC 的默认行为是显示一条警告,内容为“内置函数的不兼容隐式声明”,无论是否存在强制转换。
  • 如果指针的类型发生变化,则必须修复所有malloc被调用和转换的代码行(除非它被转换为 a typedef)。


1. Emphases are mine.

1. 重点是我的。

回答by Paul92

As the return type of malloc is void*, when you assign the result to a pointer, it is converted implicitly to the new type. So, there is no need for explicit casting. Actually, using an explicit cast is discouraged, as described here.

由于 malloc 的返回类型是 void*,因此当您将结果分配给指针时,它会隐式转换为新类型。因此,不需要显式转换。事实上,使用一个明确的投气馁,描述在这里

回答by Thomas Padron-McCarthy

mallocreturns void*, which is a generic pointer that can point to any type of data. The (char*)is an explicit type conversion, converting the pointer returned by malloc from a pointer to anything, to a pointer to char. This is unnecessary in C, since it is done implicitly, and it is actually recommended not to do this, since it can hide some errors.

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

If you need the code to compile as C++ too, and not just as C, you will however need the explicit conversion, since C++ doesn't perform the implicit conversion.

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

回答by Barath Ravikumar

malloc()return a void*, as malloc()does not know how its caller will be using the memory it allocated on the heap. So it's up to you, the caller to cast the (void*), into the appropriate type of pointer, that you want to use inside the memory. (int*)to store integers. (char*)to store characters etc..

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

Having said so, you don't have to explicitly cast the return of a malloc()call. And in some cases, doing so may result in bugs.

话虽如此,您不必显式转换malloc()调用的返回。在某些情况下,这样做可能会导致错误。

Kindly read up the issue here

请阅读这里的问题

What's wrong with casting malloc's return value?

强制转换 malloc 的返回值有什么问题?

Specifically, what's dangerous about casting the result of malloc?

具体来说,转换 malloc 的结果有什么危险?