Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 544
Elmi Avatar asked May 12 '16 12:05

Elmi


People also ask

Which type of memory is fragmentation?

Fragmentation is of three types: External Fragmentation. Internal Fragmentation. Data Fragmentation (which exists beside or a combination)

What are two types of memory fragmentation?

There are two types of fragmentation in OS which are given as Internal fragmentation, and External fragmentation.

What causes fragmented memory?

Fragmentation is thought to result from a lack of elaboration of the memory due to high emotion and dissociation during the traumatic experience (e.g., van der Kolk, 1987).


1 Answers

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.

like image 125
nalzok Avatar answered Sep 23 '22 03:09

nalzok