I am wondering what will happen if I attempt to realloc() a pointer that has been incremented. For example
char *ptr = NULL;
size_t siz = 256;
ptr = malloc(siz);
ptr = realloc(ptr + 5, siz * 2);
What will the return value of the realloc()
call be? I also know that realloc()
's documentation states that the pointer passed to it must have been returned by malloc(), calloc()
, or realloc()
. I am assuming that means I cannot realloc()
an incremented pointer but I have been unable to verify that assumption.
That wouldn't work any predictable way, the results would be undefined. The 1st argument you pass to realloc
or free
must be returned by malloc
, realloc
or calloc
, or it must be NULL
.
In this case it is not true for ptr[5]
, because ptr[5]
is uninitialized. You will also get a compile error or warning, because ptr[5]
is not a pointer. But even if it was a pointer (e.g. char **ptr;
), it would still be uninitialized, so the condition is false, and thus the results are undefined, and most probably the process would crash.
In this case it is not true for ptr + 5
either, because ptr + 5
is was not returned by malloc
, realloc
or calloc
(but ptr
was), and it's not NULL
. The behavior is undefined in this case, most probably the process would crash.
malloc
family function allocates memory and then returns pointer to that block. ptr + 5
is not returned by malloc
, so you can not pass it to realloc
as it expects its first argument to be a pointer return by calloc
or malloc
or realloc
itself. It will invoke undefined behavior.
[...]Otherwise, if the argument does not match a pointer earlier returned by a memory management function, or if the space has been deallocated by a call to
free
orrealloc
, the behavior is undefined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With