Some time ago a friend of mine told me not to use realloc
because it's unsafe, but he couldn't tell me why, so I made some research on the subject and the nearest references to my doubt were:
I want to know if I can continue to use realloc
in my code or if it's unsafe is there any other way to reallocate memory?
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;