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?
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;
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
* */
realloc?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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With