why free() need not take size as argument?
Hi All
I have a question Why allocating memory using malloc() we have to pass the size. But while freeing the same memory we don't need to pass the size.How the os know how much memory to be freed? What will happen in a situation like this? Code:
p = malloc(100) Thanks in advance for you help |
Quote:
Quote:
Quote:
|
Two interesting questions.
First of all, malloc and free are handled by the C library, not the kernel (or OS, taken to be synonymous with kernel in this context). What happens is that when you call malloc(n), the malloc code finds some free space; if it's short on free space, it requests some space from the OS. Malloc then creates a node for a linked list, the size of which is n plus room for overhead. The overhead stores the two pointers for the linked list, plus the size. When you call free, you pass a pointer that points 12 bytes into a big node. Free can subtract 12 from your pointer and get the address of the node, from which it can read the size. So that's why you don't need to tell the size to free: it already knows. Parent poster talked about pages. They *do* enter the picture: when malloc talks to the kernel, if the kernel hands out memory to your program, it will hand it out in chunks of a fixed size. These chunks are called pages, as parent said, and typically have a size of 4K bytes. How your program manages that memory is up to your program; malloc does it on your behalf, in the case of C, but there's nothing stopping you from talking to the kernel directly. What happens when you call free(1 + malloc(n))? Most likely, your program will crash; either free will try to read a bad pointer, or it will check that the pointer is bad, spew out an error message and die. |
All times are GMT -5. The time now is 09:15 AM. |