开发者

Why doesn't a call to free() reduce the size of the heap?

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?


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 sbrk with 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 the malloc arena(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:

for (int i = 0; i < 1000; i++) {
    char *m = malloc (1000000);
    free (m);
}

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 malloc uses sbrk at all. Modern operating systems may provide better alternatives due to the disconnect between logical and physical memory.


When you ask for memory (using malloc for example) it has two choices:

  • If it already has enough space "reserved" it just gives you that memory
  • If not it goes and asks the operating system (using a system call)

When you free the memory, the same mechanism keeps it around, in case you ask for it later. Constantly bothering the OS by asking for memory / relinquishing memory wouldn't be efficient.

Obviously, since you are talking about C, it is worth mentioning that no standard will ever enforce any such behavior.


In general it doesn't make a lot of sense to use sbrk() in the first place, these days. For a more in depth discussion of that function, see this question.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜