I've figured that malloc takes more time, but my question is more technical and refers to what malloc actually does that makes him slow.
Printable View
It's slow because it's designed for all kinds of usage scenarios. For example, my example above won't work if you need more than 1024 bytes of memory, or if you need to allocate and deallocate memory (my implementation doesn't provide a free). When you provide a free and actually want to use the memory freed, you will be dealing with a much nastier problem, as you will need to decide how to give out the uncontinuous memory chunks. And also, you need to take care to not make the memory segmented too much, or else you will end up with many small chunks, and when the program requests a big block, it will fail, even if the sum of free memory still well exceeds the size of the requested block. That's why complicated memory management algorithms have to be used in malloc. Take all that into consideration, and you will have something as "slow" as malloc.
*edit*
A more practical implementation of memory pool would be when you know your program only needs constant sized chunks. You can just malloc a huge array in the initialization routine, and keep a stack of pointers to available chunks. To alloc, pop and return a pointer from the stack. To dealloc, push the pointer back to the stack. Using a FILO stack works best because chances are the more recently allocated chunks are still in CPU cache. It would still be a lot faster than malloc, but not as fast as the memory pool in my post above. And it assumes that you only need chunks of one size. When you are allowed to alloc arbitrarily sized chunks (as in the case of malloc), it gets a lot more complicated (and slower).
*/edit*
Btw I think memory pooling could be another way to avoid memory leaks in your program, isn't right?
Could be. If done correctly and the context allows it (such as the one in my post above). It doesn't "avoid" memory leaks, though. It just deallocates the whole big chunk at once at the end.
Not worth the trouble IMHO to use a memory pool to "simplify" memory management.
There are much easier ways to prevent memory leaking. Smart pointers, or even using a garbage collector (although rather rare for C/C++ programs).
Hey! Another cool topic?Quote:
There are much easier ways to prevent memory leaking. Smart pointers, or even using a garbage collector (although rather rare for C/C++ programs).
What is it? Any example in C?
Ah, sorry, forgot this is the C forum. It's a C++ thing =P. I'm not aware of smart pointers in C.
It's basically a pointer that deallocates the memory it points to when it goes out of scope.
Smart pointers are RAII using C++, that simplifies memory management a lot.
C doesn't have this capability since it's too low level.