Do we lose data in a buffer after realloc'ing?

user1129665 picture user1129665 · Feb 4, 2012 · Viewed 22.8k times · Source

I'm having troubles understanding how realloc works. If I malloc'ed a buffer and copied data to that buffer, let's say "AB":

 +------------+
 | A | B | \0 |
 +------------+

then I realloc'ed the buffer, will there be any lost in the data (even a single byte)?; or it just does expanding the buffer? :

 +------------------------+
 | A | B | \0 | ? | ? | ? |
 +------------------------+

code:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int main(void){

    char* buffer    = (char*) malloc( sizeof(char) * 3 );
    strncpy(buffer, "AB", 2);

    buffer          = (char*) realloc(buffer, sizeof(char) * 6); /* Will there be any lost here? */
    free(buffer);
    return(0);
}

Answer

David Heffernan picture David Heffernan · Feb 4, 2012

A realloc that increases the size of the block will retain the contents of the original memory block. Even if the memory block cannot be resized in placed, then the old data will be copied to the new block. For a realloc that reduces the size of the block, the old data will be truncated.

Note that your call to realloc will mean you lose your data if, for some reason the realloc fails. This is because realloc fails by returning NULL, but in that case the original block of memory is still valid but you can't access it any more since you have overwritten the pointer will the NULL.

The standard pattern is:

newbuffer = realloc(buffer, newsize);
if (newbuffer == NULL)
{
    //handle error
    return ...
}
buffer = newbuffer;

Note also that the casting the return value from malloc is unnecessary in C and that sizeof(char) is, by definition, equal to 1.