Reputation:
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?
Upvotes: 4
Views: 159
Reputation:
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.
Upvotes: 2
Reputation: 172378
This is an undefined behavior
as you if you think that you have obtained a pointer from malloc()
which is wrong.
Clearly x
was returned by malloc
and its value was changed before calling realloc()
Hence it is showing the undefined behavior.
Upvotes: 1
Reputation: 7610
char *x=malloc(100);
x++;
x=realloc(x, 200);
In the code shown above the address pointed by the pointer x
is changed before invoking the realloc()
function. This is undefined behavior in C.
Upvotes: 2
Reputation: 145829
See C Standard (C99, 7.20.3.4p3) on realloc
and my emphasis:
void *realloc(void *ptr, size_t size);
If ptr is a null pointer, the realloc function behaves like the malloc function for the specified size. Otherwise, if ptr does not match a pointer earlier returned by the calloc, malloc, or realloc function, or if the space has been deallocated by a call to the free or realloc function, the behavior is undefined.
In your case x
was returned by malloc
, not x + 1
. So your program invokes undefined behavior.
Upvotes: 7