cmemorymallocmemory-fragmentation

Memory fragmentation


When I use malloc()s and free()s randomly, nested and with different sizes, at some point the memory will be fragmented because these operations leave a large list of small memory areas behind that are non-contiguous and therefore can't be allocated as one bigger piece.

A few questions on this:


Solution

  • As per ISO/IEC 9899:201x -> 7.22.3

    The order and contiguity of storage allocated by successive calls to the aligned_alloc, calloc, malloc, and realloc functions is unspecified.

    A good memory manager will be able to tackle the issue to an extent. However, there are other aspects like data alignment [1] which causes internal fragmentation.

    What you could do if you rely on inbuilt memory management?

    1. Use a profiler - say valgrind - with memory check option to find the memory which is not freed after use. Example:

       valgrind --leak-check=yes myprog arg1 arg2
      
    2. Follow good practices. Example - In C++, if you intend others to inherit from your polymorphic class, you may declare its destructor virtual.

    3. Use smart pointers.

    Notes:

    1. Internal fragmentation.

    2. If you were to use your own memory management system, you may consider Boehm-Demers-Weiser garbage collector.

    3. Valgrind Instrumentation Framework.

    4. Memory not freed after use will contribute to fragmentation.