Does realloc overwrite old contents? Does realloc overwrite old contents? c c

Does realloc overwrite old contents?


Don't worry about the old contents.

The correct way to use realloc is to use a specific pointer for the reallocation, test that pointer and, if everything worked out ok, change the old pointer

int *oldpointer = malloc(100);/* ... */int *newpointer = realloc(oldpointer, 1000);if (newpointer == NULL) {    /* problems!!!!                                 */    /* tell the user to stop playing DOOM and retry */    /* or free(oldpointer) and abort, or whatever   */} else {    /* everything ok                                                                 */    /* `newpointer` now points to a new memory block with the contents of oldpointer */    /* `oldpointer` points to an invalid address                                     */    oldpointer = newpointer;    /* oldpointer points to the correct address                                */    /* the contents at oldpointer have been copied while realloc did its thing */    /* if the new size is smaller than the old size, some data was lost        */}/* ... *//* don't forget to `free(oldpointer);` at some time */


It grows already-allocated memory without overwriting existing content, or (if it's unable to grow) it allocates new larger memory at a different location and copies existing contents from previous memory into new memory.


You should program as if the old pointer is overwritten, yes. The old memory is no longer allocated so can be re-allocated by another part of your program (or a system thread for example) and written over at any time after you call realloc.

The new memory will always contain the same data that was present in the old memory though (it is copied for you if necessary), but only up to the size of the old block, any extra space allocated at the end will be uninitialised.

If you want a copy then do a new malloc and use memcpy.

Implementation-wise, when you call realloc to increase the size, one of these things might happen:

  • A new block is allocated and the contents of the old memory copied, the old block is freed, the new pointer is returned.
  • If the area after the block is not allocated, the existing block may be extended and the same pointer returned.

Since you have no way of knowing which has happened, or even if a completely different implementation to that suggested above is used, you should always code according to the spec of realloc, which is that you must not use the old pointer any more and you must use the new one.