Search code examples
cmallocfreedynamic-memory-allocationrealloc

Malloc, Realloc, Free


int *p=malloc(20);

Now Heap will allocate memory of 20 bytes. And returns the address of 1st byte to pointer p.(Assuming no NULL pointer is returned).

Now I do this,

int *q=realloc(p, 40);

Now their are following possibilities:

1]. q=p

2]. q!=p

3]. q=NULL

Forgot about Possibility 2 and 3.

Now I write:

free(p);

Now What will happen?

Will First 20 bytes will become free and rest will still remain allocated or all the 40 bytes will get free or something else?


Solution

  • The call to free will cause undefined behavior. Here is the reasoning:

    The function realloc will deallocate1 the space pointer to by pointer p.

    The lifetime2 of an object, p pointed to, ends at the deallocation.

    The function free receives a pointer to deallocated space and causes undefined behavior3.

    Additionally, the value of the pointer p after the realloc call is indeterminate and its usage may cause undefined behavior due to trap representations.

    In other words, even if the pointer returned from realloc points to the start of the same space as pointer p did, the object allocated by realloc counts as a new object with new lifetime, and may not be deallocated using the pointer p.


    1 (Quoted from: ISO/IEC 9899:201x 7.22.3.5 The realloc function 2)
    The realloc function deallocates the old object pointed to by ptr and returns a pointer to a new object that has the size specified by size.

    2 (Quoted from: ISO/IEC 9899:201x 7.22.3 Memory management functions 1)
    The lifetime of an allocated object extends from the allocation until the deallocation

    3 (Quoted from: ISO/IEC 9899:201x 7.22.3.3 The free function 2)
    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.

    4 (Quoted from: ISO/IEC 9899:201x 6.2.4 Storage duration of objects 2)
    The value of a pointer becomes indeterminate when the object it points to (or just past) reaches the end of its lifetime.