Search code examples
crealloc

Does realloc overwrite old contents?


When we reallocate memory via realloc(), are the previous contents over-written? I am trying to make a program which reallocates memory each time we enter the data into it.

Please tell me about memory allocation via realloc, is it compiler dependent for example?


Solution

  • 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 */