Reputation: 30283
My friend implemented a dynamic array to learn C. When out of allocated memory, he doubles the allocated space.
We watched his test program write 4 GB of random characters (to avoid memory compression), char by char. But the Activity Monitor (on Mac, based on top
) showed memory usage increasing gradually, not doubling on each extend.
Yet on deletion/compaction, memory usage would drop immediately and exactly as the code would free memory.
How does top track "actual" memory used within an allocated range? And why would it do this, if the rest of the allocated space isn't available for use by other processes anyway?
Upvotes: 1
Views: 128
Reputation: 241861
Most modern operating systems allocate real memory lazily, only providing the memory when an attempt is made to use it. You can increase the heap as much as you want without using any memory at all; the only effect is to allocate virtual memory addresses.
Only when you actually touch a page, for example by writing to it, is the memory actually given to the process.
One of the consequences is that malloc()
can succeed even if no physical memory is available.
If you actually use top
you will see both the virtual memory allocation (which is only an allocation of virtual addresses) and the memory actually in use (the "resident set").
Upvotes: 3