Is it safe to use realloc?

It’s perfectly safe to use realloc. It is the way to reallocate memory in a C program.

However you should always check the return value for an error condition. Don’t fall into this common trap:

p = realloc(p, new_size); // don't do this!

If this fails, realloc returns NULL and you have lost access to p. Instead do this:

new_p = realloc(p, new_size);
if (new_p == NULL)
    ...handle error
p = new_p;

Leave a Comment