Search code examples
c++cmallocfree

How many bytes will be deallocated with free() after changing the pointer?


I have following piece of code.

char* p = malloc(10);
p = p + 1;
free(p);

In above code,

  1. How does malloc return the memory address when call malloc(10)?
  2. How many bytes will be deallocated with free(p)?
  3. How does free() know how many bytes to be deallocated?

Solution

  • As the man page for free will tell you, any argument except a pointer returned from malloc has undefined behaviour:

    The free() function frees the memory space pointed to by ptr, which must have been returned by a previous call to malloc(), calloc() or realloc(). Otherwise, or if free(ptr) has already been called before, undefined behavior occurs. If ptr is NULL, no operation is performed

    Regarding how free knows the size of the block: a typical memory allocator implementation has a header for each block (containing size, freelist pointers, etc.) and free knows the size of this header and the offset from the pointer returned by malloc.

    This also answers your first question: malloc allocates such a block and returns a pointer to the start of the actual object.