Checking that `malloc` succeeded in C

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

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

how to check success?

+7
source share
4 answers

malloc returns a null pointer on error. So, if you received not null, then it points to a valid memory block.

Since NULL evaluates false in an if , you can test it very simply:

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

User Page:

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

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

The code you already tested for the error, although I usually write the assignment and check as two separate lines:

 new_list = malloc(sizeof *new_list); if (!new_list) /* error handling here */; 

(pay attention to two small changes - you should not specify the return value, and we take the size of the variable, not its type, to reduce the likelihood of a mismatch).

If malloc() does not work, it returns a null pointer, which is the only pointer value that is false.

The error handling you have is simply return -1; - how do you deal with what is really up to you in the calling function.

0
source

All Articles