malloc_trim()可以从堆中间释放内存吗? [英] Can malloc_trim() release memory from the middle of the heap?

查看:2878
本文介绍了malloc_trim()可以从堆中间释放内存吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对glibc中实现的malloc_trim的行为感到困惑.

I am confused about the behaviour of malloc_trim as implemented in the glibc.

man malloc_trim
[...]
malloc_trim - release free memory from the top of the heap
[...]
This function cannot release free memory located at places other than the top of the heap.

当我现在查找malloc_trim()的源(在malloc/malloc.c中)时,我看到它调用了mtrim(),它利用madvise(x, MADV_DONTNEED)将内存释放回操作系统.

When I now look up the source of malloc_trim() (in malloc/malloc.c) I see that it calls mtrim() which is utilizing madvise(x, MADV_DONTNEED) to release memory back to the operating system.

所以我想知道手册页是否错误,或者我是否在malloc/malloc.c中误解了源代码.

So I wonder if the man-page is wrong or if I misinterpret the source in malloc/malloc.c.

malloc_trim()可以从堆中间释放内存吗?

Can malloc_trim() release memory from the middle of the heap?

推荐答案

...利用madvise(x,MADV_DONTNEED)将内存释放回 操作系统.

... utilizing madvise(x, MADV_DONTNEED) to release memory back to the operating system.

madvise(x, MADV_DONTNEED)不会释放内存. man madvise:

MADV_DONTNEED
不要指望在不久的将来访问. (暂且, 应用程序在给定范围内完成,因此内核 可以释放与其关联的资源.)后续访问 此范围内的页面会成功,但会导致 从底层映射文件重新加载内存内容 (请参见 mmap (2))或按需按需填充的页面(不含映射) 基础文件.

MADV_DONTNEED
Do not expect access in the near future. (For the time being, the application is finished with the given range, so the kernel can free resources associated with it.) Subsequent accesses of pages in this range will succeed, but will result either in reloading of the memory contents from the underlying mapped file (see mmap(2)) or zero-fill-on-demand pages for mappings without an underlying file.

因此,madvise(x, MADV_DONTNEED)的用法与man malloc_trim的声明并不矛盾:

So, the usage of madvise(x, MADV_DONTNEED) does not contradict man malloc_trim's statement:

此功能无法释放位于堆顶部以外的其他位置的可用内存.

This function cannot release free memory located at places other than the top of the heap.

这篇关于malloc_trim()可以从堆中间释放内存吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆