Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

checking that `malloc` succeeded in C

Tags:

c

malloc

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?

like image 286
SIMEL Avatar asked Apr 09 '11 19:04

SIMEL


1 Answers

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
}
like image 85
Etienne de Martel Avatar answered Oct 14 '22 09:10

Etienne de Martel