In C, is passing a void * as an argument to a free function bad practice? If not, how will the function know how much memory to free starting from the location that void * points to?
In C, is passing a void * as an argument to a free function
Share
free()only needs the start address of the memory block; its contents don’t matter. That’s why it actually has avoid*in its signature (so it doesn’t matter what kind of pointer you pass, it will always get avoid*).As you can see you may only free memory allocated by one of these functions – and they store the size of the block internally.
In case you are curious, the information doesn’t even need to be stored in a separate structure at a single location; for example it’s common for various replacements of the default
malloc/freeto allocate N+M bytes of memory with M being the size of the metadata struct. At the address returned by that allocation they store their own metadata (such as the allocated size) and then return ptr+M which points to the memory right after the metadata.When freeing that memory it can simply subtract M from the address to get the initial pointer, which points to the metadata.