C语言 检查 `malloc` 在 C 中是否成功
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5607455/
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
checking that `malloc` succeeded in C
提问by SIMEL
I want to allocate memory using mallocand check that it succeeded. something like:
我想使用分配内存malloc并检查它是否成功。就像是:
if (!(new_list=(vlist)malloc(sizeof (var_list))))
return -1;
how do I check success?
我如何检查成功?
回答by Etienne de Martel
mallocreturns a null pointer on failure. So, if what you received isn't null, then it points to a valid block of memory.
malloc失败时返回空指针。因此,如果您收到的内容不为空,则它指向一个有效的内存块。
Since NULLevaluates to false in an ifstatement, you can check it in a very straightforward manner:
由于NULL在if语句中求值为 false ,您可以以非常简单的方式检查它:
value = malloc(...);
if(value)
{
// value isn't null
}
else
{
// value is null
}
回答by Spyros
Man page :
手册页:
If successful,
calloc(),malloc(),realloc(),reallocf(), andvalloc()functions return a pointer to allocated memory. If there is an error, they return aNULLpointer and seterrnotoENOMEM.
如果成功,
calloc()、malloc()、realloc()、reallocf()和valloc()函数返回指向已分配内存的指针。如果有错误,它们返回一个NULL指针并设置errno为ENOMEM。
回答by jdehaan
new_list=(vlist)malloc(sizeof (var_list)
if (new_list != NULL) {
/* succeeded */
} else {
/* failed */
}
回答by Toby Speight
The code you have already tests for error, although I normally write the assignment and check as two separate lines:
您已经测试过错误的代码,尽管我通常将赋值和检查作为两行单独编写:
new_list = malloc(sizeof *new_list);
if (!new_list)
/* error handling here */;
(Note two small changes - you shouldn't cast the return value, and we take the size from the variable rather than its type to reduce the chance of a mismatch).
(注意两个小的变化——你不应该强制转换返回值,我们从变量而不是它的类型中获取大小以减少不匹配的机会)。
If malloc()fails, it returns a null pointer, which is the only pointer value that is false.
如果malloc()失败,它返回一个空指针,这是唯一为false 的指针值。
The error handling you have is simply return -1;- how you handle that in the calling function is up to you, really.
你所拥有的错误处理很简单return -1;——你如何在调用函数中处理它,真的取决于你。

