Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does free know how much to free?

In C programming, you can pass any kind of pointer you like as an argument to free, how does it know the size of the allocated memory to free? Whenever I pass a pointer to some function, I have to also pass the size (ie an array of 10 elements needs to receive 10 as a parameter to know the size of the array), but I do not have to pass the size to the free function. Why not, and can I use this same technique in my own functions to save me from needing to cart around the extra variable of the array's length?

like image 372
Joshua Cheek Avatar asked Oct 05 '09 07:10

Joshua Cheek


People also ask

How does the free function know how much memory to free?

The free() function is used to deallocate memory while it is allocated using malloc(), calloc() and realloc(). The syntax of the free is simple. We simply use free with the pointer. Then it can clean up the memory.

How does malloc know memory to free when a user calls free on a pointer?

For the case of malloc , the heap allocator stores a mapping of the original returned pointer, to relevant details needed for free ing the memory later.

What does free actually do?

What is free Function in C? The free() function in C library allows you to release or deallocate the memory blocks which are previously allocated by calloc(), malloc() or realloc() functions. It frees up the memory blocks and returns the memory to heap.

How does the free function work in C?

free() function in C should only be used either for the pointers pointing to the memory allocated using malloc() or for a NULL pointer. free() function only frees the memory from the heap and it does not call the destructor. To destroy the allocated memory and call the destructor we can use the delete() operator in C.


1 Answers

When you call malloc(), you specify the amount of memory to allocate. The amount of memory actually used is slightly more than this, and includes extra information that records (at least) how big the block is. You can't (reliably) access that other information - and nor should you :-).

When you call free(), it simply looks at the extra information to find out how big the block is.

like image 187
Gary McGill Avatar answered Sep 29 '22 06:09

Gary McGill