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?
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?
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
}
Man page :
If successful,
calloc()
,malloc()
,realloc()
,reallocf()
, andvalloc()
functions return a pointer to allocated memory. If there is an error, they return aNULL
pointer and seterrno
toENOMEM
.
new_list=(vlist)malloc(sizeof (var_list)
if (new_list != NULL) {
/* succeeded */
} else {
/* failed */
}
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.