Search code examples
crealloc

Understanding realloc() in C


In this example from: http://www.cplusplus.com/reference/cstdlib/realloc/ why are there two pointers: numbers and more_numbers? Can I use:

numbers = (int*) realloc (numbers, count * sizeof(int));
if (numbers!=NULL) {
       numbers[count-1]=input;
}
else {
       free (numbers);
       puts ("Error (re)allocating memory");
       exit (1);
}

Solution

  • To see why your version is wrong, you need to realise what realloc does. It does one of two things: If there is enough memory, it will return a new pointer and the old one becomes invalid. If there isn't enough memory, it will return NULL and the old pointer stays valid and unchanged.

    You must store the result of realloc into a temporary variable, and not overwrite the old pointer. The reason is that if realloc returns NULL, and you overwrote the old pointer with NULL, you lost access to your existing data. So the correct way is:

    int* tmp = (int*) realloc (numbers, count * sizeof(int));
    if (tmp!=NULL) {
        // realloc was successful. The old value of numbers is now rubbish. 
        // Store the result of realloc into numbers and continue. 
        numbers = tmp; 
        numbers[count-1]=input;
    }
    else {
        // realloc failed. The old value of numbers is unchanged but doesn't have enough
        // space to store input. You need to handle the error somehow. 
        free (numbers);
        puts ("Error (re)allocating memory");
        exit (1);
    }
    

    If you had stored the realloc () result directly into numbers, the "else" branch wouldn't know the old value of numbers anymore and couldn't free that memory.