Memory fragmentation
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?
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
Follow good practices. Example - In C++, if you intend others to inherit from your polymorphic class, you may declare its destructor virtual.
Use smart pointers.
Notes:
Internal fragmentation.
If you were to use your own memory management system, you may consider Boehm-Demers-Weiser garbage collector.
Valgrind Instrumentation Framework.
- Memory not freed after use will contribute to fragmentation.
No, there is no guarantee. According to N1570, 7.22.3 Memory management functions:
The order and contiguity of storage allocated by successive calls to the aligned_alloc, calloc, malloc, and realloc functions is unspecified.
Anyway, you have two choices to choose from:
- Totally trust the library memory management functions.
- Write you own memory managers, if you're really confident.
If I were you, I would definitely trust the existing functions, because modern implementations are super smart.