如何知道应用程序内部的可用虚拟内存 [英] How to know the available virtual memory inside an application

查看:138
本文介绍了如何知道应用程序内部的可用虚拟内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

按照标题的要求,

是否可能知道当前可用的虚拟内存 (可通过malloc/mmap分配)在应用程序内部 以编程方式?

Is it possible to know the currently available virtual memory (which is allocatable by malloc/mmap) inside an application by programmatically?

我正在寻找的是某种功能

What I'm looking for is some kind of a function

unsigned int free_mem();

将返回可通过malloc或mmap分配的内存大小.

which will return the size of memory allocatable by malloc or mmap.

推荐答案

由于您在明确地讨论可用的虚拟内存,因此需要查找虚拟地址空间中当前未分配的部分.段信息可在proc/self/smaps中找到.

Since you are explicitly talking about available virtual memory, you need to find the parts of the virtual address space which are currently unallocated. Segment information is available in proc/self/smaps.

但是,虚拟地址空间的大小由程序在其上执行的cpu决定.在64位处理器上,这不是64位,但可以由cat /proc/cpuinfo | grep "address sizes"确定,该结果会产生

However, the size of the virtual address space is determined by the cpu your program is executing on. This is not 64 bits on a 64 bit processor, but can be determined by cat /proc/cpuinfo | grep "address sizes" which yields

address sizes   : 42 bits physical, 48 bits virtual
address sizes   : 42 bits physical, 48 bits virtual
address sizes   : 42 bits physical, 48 bits virtual
address sizes   : 42 bits physical, 48 bits virtual
address sizes   : 42 bits physical, 48 bits virtual
address sizes   : 42 bits physical, 48 bits virtual
address sizes   : 42 bits physical, 48 bits virtual
address sizes   : 42 bits physical, 48 bits virtual

在我当前正在对其进行测试的VM上.

on the VM I am currently testing it on.

请注意,由于您只能映射连续的内存量,因此可用虚拟地址空间的总量与一次可以分配的最大虚拟地址空间不同.

Note that the total amount of available virtual address space is different from the largest amount allocatable in one go, since you can only mmap a sequential amount of memory.

例如,考虑具有以下段的32位指针的简单情况:

For example consider the simple case of 32 bit pointers with the following segments:

00020000-000204ff /usr/bin/executable
00030000-0003ffff [heap]
7ff80000-7ff9ffff [stack]

在这种情况下,最大的连续段是7ffA000-ffffffff,但是可用虚拟内存的总量仅略少于4 GB.

In this case the largest continuous segment is 7ffA000-ffffffff, but the total amount of available virtual memory is only slightly less than 4 GB.

还请注意,malloc可以通过重用已请求的页面来满足您的请求,而无需更多的虚拟内存.这种方式可用的数量取决于很多因素(一个或多个分配的大小,堆的状态),并且无法以任何可移植的方式进行查询.如果某人 LD_PRELOAD是另一个malloc实现,则此方法会加倍.

Note also that malloc may be able to satisfy your request without requiring more virtual memory by reusing already requested pages. The amount available this way depends on a many things (size of the allocation or allocations, state of the heap) and cannot be queried in any portable way. This holds double if someone LD_PRELOADs another malloc implementation.

这篇关于如何知道应用程序内部的可用虚拟内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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