Alan Salios
Alan Salios

Reputation: 243

Reallocate block of allocated memory different than its offset

What will happen if I reallocate a specific block of memory of a previously allocated memory area?


#include <stdlib.h>

int main(void)
{
    char *area = malloc(15 + 1);

    strcpy(area, "Stack / Overflow");
    realloc(area + 5, strlen(area) + 5);

    return EXIT_SUCCESS;
}

Will the area string be expanded with 5 bytes in this example?

Idx: 0  1  2  3  4  5  6  7  8  9  10  11  12  13  14  15  16  17  18  19  20  21
Chr: S  t  a  c  k  \0 \0 \0 \0 \0     /       O   v   e   r   f   l   o   w   \0

Upvotes: 2

Views: 614

Answers (2)

Frankie_C
Frankie_C

Reputation: 4877

The heap manager when allocates a memory blocks keep track of each allocated chunk in order to handle successive reallocations or releases of chunks. So the memory allocator knows very well which memory belongs to it and could be legally resized or released (normally the manager for each allocation builds also an hidden control block where are saved all block properties). While the standards C99 C11 still assume an undefined behavior for invalid pointers actually almost all C & C++ libraries implementations throw an exception in such a case.

Upvotes: 0

Sourav Ghosh
Sourav Ghosh

Reputation: 134346

Undefined behaviour. realloc() needs a pointer returned by malloc() or family or a NULL.

As per the c99, chapter 7.20.3.4, paragraph 3, for void *realloc(void *ptr, size_t size); [emphasis mine]

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. If memory for the new object cannot be allocated, the old object is not deallocated and its value is unchanged.


Other than this, in your code

char *area = malloc(15 + 1);
strcpy(area, "Stack / Overflow");

you're not allocating space for terminating null. Result can be devastating. Please add space to store terminating \0.

Also, while using realloc(), please notice the second parameter. It should be the new size [in total], not the difference from the current allocation size. [Code snippet updated by OP]

Again, you have to use the return value of realloc() to access the newly allocated memory. The old pointer may not be valid anymore. Please read the man page for details.

So for you, the code should look like

#include <stdlib.h>

int main(void)
{
    char *area = malloc(17);   //space for terminating null
    char * area_next = NULL;


    strcpy(area, "Stack / Overflow");   //cpy 16 chars, with null
    area_next = realloc(area, 23);                  // oldsize + 5

    return EXIT_SUCCESS;
}

Upvotes: 5

Related Questions