Static memory preallocation
Projects that either do not need the complexity of a full heap or can't afford the risk of fragmentation, can use a technique that allows allocation, but not freeing. This means that after a program has completed its initialization code, the main loop of the program (or the loop of each of its tasks) will not allocate any further memory. This technique can be implemented with the normal
malloc() routine, but I've always found it useful to write a custom version. My custom version has the following advantages over using the normal
malloc() routine:
- The overhead of the headers on each block is avoided.
- The routine can be disabled once initialization is complete.
This technique also has the following advantages over declaring all memory globally.
- Different start-up sequences can allocate memory to different purposes, without the programmer having to explicitly consider which items can be active simultaneously.
- The namespace does not get polluted as much. In many cases, a pointer to an item may exist, but there is no need for a global or file static to exist for the item itself. Creating the global or file static allows access to the item from inappropriate parts of the code.
- It is easy to transition to using a free() function later.