Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

realloc() an incremented pointer

Tags:

c

malloc

  • Platform: Linux 3.2.0 x86 (Debian Wheezy)
  • Compiler: GCC 4.7.2 (Debian 4.7.2-5)

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.

like image 230
John Vulconshinz Avatar asked Jan 10 '23 09:01

John Vulconshinz


2 Answers

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.

like image 168
pts Avatar answered Jan 22 '23 20:01

pts


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 mallocor realloc itself. It will invoke undefined behavior.

C11: 7.22.3.3:

[...]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 or realloc, the behavior is undefined.

like image 24
haccks Avatar answered Jan 22 '23 21:01

haccks