We know that the stack of a program will grow or shrink when it runs. In a C program, when we use malloc() to allocate memory, if current memory is not enough, it will call sbrk() to extend the heap size. When we use free() to release allocated memory, it doesn’t shrink the heap. Why doesn’t it make sense to shrink the heap?
We know that the stack of a program will grow or shrink when it
Share
The stack does not shrink. Your use of the stack may be variable but the stack itself generally stays constant in size.
And you can shrink the heap by calling
sbrkwith a negative argument but I suspect the main reason that’s not done is because the process may need the memory again at some point. It can take time to adjust themallocarena(s) when the underlying memory changes.When you need more memory, that’s fine, you pay the price because you want something. But you don’t want to pay that price when releasing memory since you don’t need to. And, if you did, then needed that memory again, you’d be constantly paying the price. Think of the loop:
and think of how much more inefficient that would be with the extra load.
You can think of the memory freed but not released back to the operating system as your own personal cache of memory.
This is all assuming, of course, that
mallocusessbrkat all. Modern operating systems may provide better alternatives due to the disconnect between logical and physical memory.