How does free know the size of memory to be deleted.?
int *i = (int *)malloc(12); followed by free(i); how did free function call know how much of memory to delete?
A: It based on the implementation, however usually there is a malloc header added to all the memory allocated through malloc. On Linux its four bytes of memory preceding the memory returned to you, which contain the number of bytes allocated + 4(itself). Thus while you say,
int *i = (int *)malloc(12);
it allocates 16 bytes.
17 | | | |
Since you can see above total of 16 bytes are allocated, first four bytes stores the number of bytes allocated(offset to the next memory from the begin of this memory). Address of the 5th byte is returned to i. now i can access 12 bytes through this byte.