checking that `malloc` succeeded in C

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
}

Leave a Comment