简体   繁体   中英

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:

  • 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?

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:

  1. Totally trust the library memory management functions.
  2. 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM