Ilya Melamed Ilya Melamed - 1 year ago 98
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?

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download