checking that `malloc` succeeded in C

2019-01-12 03:55发布

问题:

I want to allocate memory using malloc and check that it succeeded. something like:

if (!(new_list=(vlist)malloc(sizeof (var_list))))
  return -1;

how do I check success?

回答1:

malloc returns a null pointer on failure. So, if what you received isn't null, then it points to a valid block of memory.

Since NULL evaluates to false in an if statement, you can check it in a very straightforward manner:

value = malloc(...);
if(value)
{
    // value isn't null
}
else
{
    // value is null
}


回答2:

Man page :

If successful, calloc(), malloc(), realloc(), reallocf(), and valloc() functions return a pointer to allocated memory. If there is an error, they return a NULL pointer and set errno to ENOMEM.



回答3:

new_list=(vlist)malloc(sizeof (var_list)
if (new_list != NULL) {
  /* succeeded */
} else {
  /* failed */
}


回答4:

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.

The error handling you have is simply return -1; - how you handle that in the calling function is up to you, really.



标签: c malloc