Ilya Melamed Ilya Melamed - 4 months ago 32
C Question

checking that `malloc` succeeded in C

I want to allocate memory using

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(...);
    // value isn't null
    // value is null