Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory realloc risk

I need to know, are there any risks using the realloc() function to get additional memory?

For instance , I'm storing some stream into a char* variable. The problem is that we can't specify at the beginning the maximum size of the input stream, so we need from time to time to expand the memory area.

My question is: could reallocating memory cause data loss of my reallocated variable?

like image 673
Aymanadou Avatar asked Jul 26 '26 17:07

Aymanadou


2 Answers

Can I lose data if I use it correctly?

No, there should never be any data loss when using realloc, it should be the syntactically the same as doing the below.

new_memory = malloc (new_size);

if (new_memory != NULL) {
    memcpy (new_memory, old_memory, old_size < new_size ? oldsize : new_size);
    free   (old_memory);
}

return newp;

What if reallocation fails?

If the reallocation failed (ie. no new memory could be allocated) the pointer to old_memory will still be valid, so please don't do like this:

my_memory = realloc (my_memory, new_size); 

  /*
   * if the allocation fails you will lose the pointer to your memory,
   * which will make you:
   *   a) lose your data
   *   b) have a memory leak
   * */

What does the standard say about realloc?

  • pubs.opengroup.org - realloc
like image 90
Filip Roséen - refp Avatar answered Jul 28 '26 09:07

Filip Roséen - refp


You won't lose any data calling realloc but the allocation may fail, just like a malloc. That's usually regarded as terminal. If the memory block cannot be resized in-place a new block is created and the contents of the old block copied to the new block.

like image 27
David Heffernan Avatar answered Jul 28 '26 09:07

David Heffernan