How to detect free/unfree memory segments?

Nemanja Boric via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Dec 23 05:16:05 PST 2016


I can just partially answer this part of the question:

> Could anybody explain what dangerous of memory fragmentation in 
> languages without GC? Am I right understand that there is stay 
> some small memory chunks that very hard to reuse?

On Unix-like systems, system call for allocating memory is 
traditionally `brk`/`sbrk` which just moves "program break" which 
indicates how much memory program has allocated.

Say that you're running your application, and your heap looks 
like this:

            4096
-------------------
|  heap  [myarr]  |
-------------------
                   ^
                   |
              program break

now you call `sbrk(2 * 4096)` as you need  which will allocate 
2*4096 for you:

            4096
--------------------------------------
|  heap  [myarr]    [my new array]   |
--------------------------------------
                                      ^
                                      |
                               program break

Now, if you want to discard [myarr], it will leave a hole in 
heap, since you don't want to move `[my new array]`. This hole 
can be reused, but sometimes it can't, depending on the size, etc.

That's why there's another system call you can use: mmap, which 
you would use to allocate space for `my new array`, 
non-contiguously and not adjacent to `myarr`,  and so when you 
discard myarr, you don't have fragmentation issue:

            4096
------------------                   --------------------
|  heap  [myarr]  |                  |  [my new array]   |
------------------                   --------------------
                   ^
                   |
                 program break


These, and many more facts (reusing freed area, when to use brk, 
when to use mmap, locking contention detection, for example) are 
used by the standard memory allocators you would use in non-GC 
program (such is malloc), so while it is possible that you will 
have memory fragmentation problems, it is very unlikely, unless 
you're writing something that's very different than vast majority 
of the programs. And in that case, there are different allocators 
that you can use, or you can write your own.

Nemanja

On Friday, 23 December 2016 at 06:18:02 UTC, Suliman wrote:
> I would like to visualize how GC works and display free/not 
> free memory segments.
> How I can understand which of them are used and which not?
>
> Could anybody explain what dangerous of memory fragmentation in 
> languages without GC? Am I right understand that there is stay 
> some small memory chunks that very hard to reuse?




More information about the Digitalmars-d-learn mailing list