I have read that malloc actually allocates (required_size + 1) blocks of memory and it stores the size in the first block and the pointer to the second block is returned. This way free() knows how much memory to free. So, I wrote a small code to output this size.
int *p = (int *)malloc(100*sizeof(int));
printf("size = %d\n",p[-1]);
Since I am allocating space for 100 ints, I am expecting the size to be 400. But the output was 409. For 50 int’s output was 209 and for 1000 int’s output was 4009. Can someone pls explain why the output is off by 9 bytes?
Assuming the implementation is glibc (or similar), the following can be found in comments in
malloc.c:That explains the existence of overhead.
Now, for the ‘off by 1’, the flags are responsible for that. Since sizes (actually) allocated by
malloc()will be always multiples of 8, the three least significant bits are used to store flags:Edit: ah, and I’d almost forgot. The size is stored as
size_t, not anint, so you should use that type to access it.