This is an implementation detail that can and can vary between different platforms. Here is one example of how this can be implemented.
Each call to free must be paired with a call to malloc / realloc , which knows the size request. The malloc implementation may choose to keep this size with the offset of the returned memory. Say, allocating a larger buffer than the requested one, gaining size in front, and then returning the offset to the allocated memory. Then, the free function could simply use the offset of the provided pointer to detect the free size.
for instance
void* malloc(size_t size) { size_t actualSize = size + sizeof(size_t); void* buffer = _internal_allocate(actualSize); *((size_t*)buffer) = size; return ((size_t*)buffer) + 1; } void free(void* buffer) { size_t* other = buffer; other--; size_t originalSize = *other;
source share