Optimize heap memory
You can use the following techniques to optimize memory usage:
- eliminate memory leaks
- shorten the life cycle of heap objects
- reduce the overhead of allocated objects
- configure the allocator
Another optimization technique is to shorten the life cycle of the heap object. This technique lets the allocator reclaim memory faster, and allows it to be immediately used for new heap objects, which, over time, reduces the maximum amount of memory required.
Always attempt to free objects in the same function as they are allocated, unless it is an allocation function. An allocation function is a function that returns or stores a heap object to be used after this function exits. A good pattern of local memory allocation will look like this:
p=(type *)malloc(sizeof(type)); do_something(p); free(p); p=NULL; do_something_else();
After the pointer us used, it is freed, then nullified. The memory is then free to be used by other processes. In addition, try to avoid creating aliases for heap variables because it usually makes code less readable, more error prone, and difficult to analyze.