Create separate heaps in C

Viewed 344

I'm working on a function that does a lot of dynamic memory allocation, however, if this function exceeds a threshold of time, the timer fires. Hence, we need to free all the memory allocated when we started this function.

We use a third party tool to create a heap pool when we enter the function. Hence, any dynamic memory allocation will be from this heap pool. If the timer fires, we just free this heap pool, and the code continues working with the heap pool before it (it is like a stack of pools).

We need to stop using this third party tool due to cost.

Does any one have a solution idea for this issue to replace this third party tool?

Note: it is not a multi-threaded system.

Thanks in advance.

2 Answers

You can acquire a large memory chunk from heap and write your own allocator and deallocator. And if the timer fire you can free the whole chunk.

Of course this will require a deep-dive into how malloc and free works. And you will need to know how and what information is stored in memory header.

You can use a pointer collection where you store all the pointers to the memory you allocate during the function and when the time is over, you go through and free all of them. (You can store any pointer as a void*, so that is possible) This has the advantage that you don't have to code manually your malloc and free. If you want to work more like the tool you were using, you can allocate a big chunk of memory, and then implement your own version of malloc and free that return a pointer to a "free" part of your block. This has the advantage that you now have to do just one free when you leave the function but at the cost of a way more complicated implementation (consider you can run out of memory and have to avoid fragmentation manually). I would suggest you the first approach.

Related