SIMEL
SIMEL

Reputation: 8931

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?

Upvotes: 15

Views: 52252

Answers (4)

Toby Speight
Toby Speight

Reputation: 30717

The code you have already tests for error, although I normally write the assignment and check as two separate lines:

new_list = malloc(sizeof *new_list);
if (!new_list)
    /* error handling here */;

(Note two small changes - you shouldn't cast the return value, and we take the size from the variable rather than its type to reduce the chance of a mismatch).

If malloc() fails, it returns a null pointer, which is the only pointer value that is false.

The error handling you have is simply return -1; - how you handle that in the calling function is up to you, really.

Upvotes: 1

Spyros
Spyros

Reputation: 48616

Man page :

If successful, calloc(), malloc(), realloc(), reallocf(), and valloc() functions return a pointer to allocated memory. If there is an error, they return a NULL pointer and set errno to ENOMEM.

Upvotes: 8

Etienne de Martel
Etienne de Martel

Reputation: 36852

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
}

Upvotes: 31

jdehaan
jdehaan

Reputation: 19928

new_list=(vlist)malloc(sizeof (var_list)
if (new_list != NULL) {
  /* succeeded */
} else {
  /* failed */
}

Upvotes: 8

Related Questions