# How free will calculate no of bytes it need to free ??

144 views
How free will calculate no of bytes it need to free ??
posted Oct 15, 2013

+1 vote

Cant stop myself to answer this question -

Say you are allocating 10 Bytes, system allocates 4+10 bytes and store the value 14 in first 4 bytes. Then return the pointer after moving 4 bytes forward. So the user get only 10 bytes.

In free you provide the pointer, control goes back by 4 bytes and read the first 4 bytes to get the length and free the 14 bytes.

Can we corrupt this 4 extra bytes that has size information ?
Its in the process space so yes...
Value of K depende on OS kit.

Actually malloc allocates memory multiple of  "K".
Means
if k=4 and you want to allocate 1 byte malloc will allocate 4 byte + no of bytes to store allocated bytes
if k=4 and you want to allocate 3 byte malloc will allocate 4 byte + no of bytes to store allocated bytes.
if k=4 and you want to allocate 5 Or 7 byte malloc will allocate 8 byte + no of bytes to store allocated bytes.

This is the reason some time segmentation fault does not comes when we access bye more than the number given in malloc.
hi salil thanks, and can you point me the book that related to these stuffs...
+1 vote

See the code below .
First 4 byes contains the no of bytes need to free.

``````void *malloc_flags(size_t size, lmm_flags_t flags)
{
oskit_size_t *chunk;
chunk = in_alloc(size + sizeof(oskit_size_t), flags);
if (chunk)
*chunk++ = size;
return chunk;
}

----------------------------------------------------------------------

void free_flags(void *chunk)
{
oskit_size_t size;
/* Posix says free of NULL does nothing */
if (! chunk)
return;
(oskit_size_t*)chunk -= 1;
size = *((oskit_size_t*)chunk);
in_free(chunk, size + sizeof(oskit_size_t));
}

=====================================================================

void *malloc(size_t size)
{
return malloc_flags(size,0);
}
---------------------------------------------------------------------

void free(void *chunk)
{
return free_flags(chunk);
}
``````