Search code examples
cpointersmallocdynamic-memory-allocationfree

How does C free all bytes of a dynamically allocated array?


#include <stdio.h>
#include <stdlib.h>

int main(){

    int * ptr = (int*)malloc(sizeof(int)*100); // Allocated space for 100 integers

    // Some code

    free(ptr); // Calling free with ptr as argument

    return 0;
}
  1. How does this free all 400 bytes (in my case)? ptr only contains address of one byte in the memory and also I have not passed any other argument specifying the size of the dynamic array so that it may run a loop and frees all the bytes

  2. What will happen if I do this:

    ptr++;
    free(ptr);
    
  3. Since we cannot retrieve the size of the array in heap by giving the pointer then it means malloc() has no clue how many bytes were reserved along with ptr then why does it not allocate another heap memory starting from the middle of previous array?


Solution

    1. Part of the malloc/free routines includes storing metadata such as how big the block of memory is so free(). Typically this data is stored at the bytes immediately before the pointer returned by malloc(). Read more here.

    2. Since the incremented value of the pointer was not one previously returned by malloc(), calloc(), or realloc(), the code ptr++; free(ptr); where ptr is returned by malloc() invokes undefined behavior. free() might try to access bookkeeping data which is assumed to be at a fixed offset from the start of the allocated block, but find garbage instead and crash violently. Or maybe something completely different happens. You cannot reliably predict what happens when undefined behavior is invoked.