Ilya Melamed Ilya Melamed - 1 month ago 11
C Question

checking that `malloc` succeeded in C

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?

Answer

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
}
Comments