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);
}
A
reallocthat 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 areallocthat reduces the size of the block, the old data will be truncated.Note that your call to
reallocwill mean you lose your data if, for some reason thereallocfails. This is becausereallocfails by returningNULL, 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 theNULL.The standard pattern is:
Note also that the casting the return value from
mallocis unnecessary in C and thatsizeof(char)is, by definition, equal to1.