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?
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.
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 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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With