Why does this code not work?
char *x=malloc(100);
x++;
x=realloc(x, 200);
I mean x is a valid string pointer, just incremented by one?
Think about what realloc
does. How can it free
the pointer at address x+1
when malloc
actually created a pointer at address x
?
In more concrete terms, let's assume you allocated 100 bytes at address 0x1000. Now x
is incremented, pointing at 0x1001. Then you call realloc
at the new address. Because none of malloc
, calloc
, and realloc
created 0x1001, free
(or equivalent code) used by the call to realloc
has no idea how to do anything with 0x1001; it can't even fathom how many bytes of memory it occupies. It only knows about the 100 bytes at 0x1000.
The basic idea behind implementations of malloc
and friends is that you keep track of the pointers assigned and how many bytes were allocated. Then when free
is called later, the pointer passed to free
is looked up. If there is no reference to that pointer passed to free
, what else is there to do except crash? That, to me, is more logical than supposing you can keep using a pointer that may or may not be valid.