Reputation: 6193
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:
When this is done quite often so that memory is forced to be fragmented and then all these memory areas are free()
d, can I assume these free areas are concatenated back to its original, contiguous size?
When I always do a malloc()
followed by free()
for the same memory and never nest these calls, is the memory fragmented in this scenario too when allocated/freed sizes are always different?
Upvotes: 18
Views: 11077
Reputation: 21955
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:
If you were to use your own memory management system, you may consider Boehm-Demers-Weiser garbage collector.
Valgrind Instrumentation Framework.
Upvotes: 4
Reputation: 16107
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:
If I were you, I would definitely trust the existing functions, because modern implementations are super smart.
Upvotes: 7