Results 1 to 3 of 3
Hi all,
When I am using malloc and free, how the compiler knows how much memory to be freed.
--Cheers
Madhu...
- 05-04-2009 #1Just Joined!
- Join Date
- May 2009
- Posts
- 21
how free() works in C
Hi all,
When I am using malloc and free, how the compiler knows how much memory to be freed.
--Cheers
Madhu
- 05-04-2009 #2
The compiler keeps a list of this, but ultimately it is the kernel that has to keep track of how much memory was reserved for the process, and where.
So if your application crashes, the kernel can still properly free all the memory.
Linux Memory Management OverviewDebian GNU/Linux -- You know you want it.
- 05-04-2009 #3Linux Guru
- Join Date
- Apr 2009
- Location
- I can be found either 40 miles west of Chicago, or in a galaxy far, far away.
- Posts
- 8,974
Generally, malloc() and free() use a pool that is allocated by the OS and provided to the application by the sbrk() function. They manage this memory as a linked list, allocating memory in chunks. So, if you allocate a single byte, you actually will get a chunk of memory up to a couple kb in size. This is why some C++ string classes have their own allocators for small strings to avoid the memory overhead associated with malloc'd memory. Anyway, it is fairly complicated to write a set of malloc/free functions that are efficient in both time and memory usage. I have written a number of allocators in the past, and all I can say to someone who is not inclined to "reinvent the wheel", is that the standard functions work, and work pretty well. Don't worry about what that guy behind the curtain is doing!
Sometimes, real fast is almost as good as real time.
Just remember, Semper Gumbi - always be flexible!


Reply With Quote