GC and memory leaks

Oskar Linde oskar.lindeREM at OVEgmail.com
Wed Nov 14 03:13:39 PST 2007


David B. Held wrote:
> Kevin Bealer wrote:
>> [...]
>> I think even malloc() does not free memory to the OS.
>> [...]
> 
> I thought that too, but I wrote a test in both C++ and D that prove that 
> malloc()/free() will return memory to the OS in both cases (at least on 
> Linux).

The glibc malloc/free/realloc implementation (used on virtually all 
Linux systems) is written by Doug Lea and follows the follows the 
following strategy:

For very large requests, >=128KB (by default), it relies (if possible) 
on mmap, while smaller requests are handled using sbrk().

Memory mapped memory is returned to the OS on free(), while sbrk() 
allocated memory is not. There are some provisions for returning sbrk() 
allocated memory to the OS, but those are disabled by default because of 
reduced performance and the fact that only freed memory chunks at the 
very top of the allocated memory range can be freed.

Those behaviors can easily be verified. Malloc()ing, then free()ing lots 
of small chunks will not return any memory to the OS(*), while doing the 
same for a few large chunks will.

However, I don't see programs keeping large unused chunks of virtual 
memory much of a problem.

*) In the case where provisions for trimming the virtual memory range is 
enabled, this behavior should still exist if if the small allocations 
are followed by one larger allocation that ends up on top of the virtual 
memory range, thereby blocking any possible trimming from happening.

-- 
Oskar



More information about the Digitalmars-d mailing list