Rules of thumb for application programmers in need of dynamic memory

  1. Malloc is generic and good. Many small allocations will work but they will slow your application down.

  2. It may be better if the application allocates a large chunk of heap and maintains it by itself. It knows best what kind of allocations will happen. Try to avoid frequent small allocations via malloc.

  3. Do not give memory back just to allocate it a few milliseconds later again. Keep your own memory pool and REUSE memory as much as possible. Caching and pooling is the name of the game for successful applications.

  4. In languages without garbage collection: Define your own memory management policy and design a coding standard with function names that make it clear when somebody takes over responsibility for a piece of memory.

    char* value = getSomething(); // does the function expect the caller to call free?
                          // is the memory area a constant and the program
                          // will crash if free(value) is called?
                          // if value will be a parameter to another call, who
                          // will take over responsibility for free-ing it?
  5. Even if you have done all this, get yourself a memory leak checker like purify which detects leaks AND overwritten memory. Leaks just slow your application down as we will see in the session on memory management. Overwritten memory is memory that got a new owner while the old one still has a reference and uses it. Or it is memory that is written beyond its boundary (like arrays).