Correct use of Realloc

realloc returns a pointer to the resized buffer; this pointer value may be different from the original pointer value, so you need to save that return value somewhere.

realloc may return NULL if the request cannot be satsified (in which case the original buffer is left in place). For that reason, you want to save the return value to a different pointer variable than the original. Otherwise, you risk overwriting your original pointer with NULL and losing your only reference to that buffer.

Example:

size_t buf_size = 0; // keep track of our buffer size

// ...

int *a = malloc(sizeof *a * some_size); // initial allocation
if (a)
    buf_size = some_size;

// ...

int *tmp = realloc(a, sizeof *a * new_size); // reallocation
if (tmp) {
    a = tmp;             // save new pointer value
    buf_size = new_size; // and new buffer size
}
else {
    // realloc failure, handle as appropriate
}

Leave a Comment