分配更多的内存比使用有存在的malloc [英] Allocating more memory than there exists using malloc
问题描述
这code段将在每次读取标准输入字母U的时间分配2GB,而一旦它读取'A'将初始化所有分配的字符。
This code snippet will allocate 2Gb every time it reads the letter 'u' from stdin, and will initialize all the allocated chars once it reads 'a'.
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <vector>
#define bytes 2147483648
using namespace std;
int main()
{
char input [1];
vector<char *> activate;
while(input[0] != 'q')
{
gets (input);
if(input[0] == 'u')
{
char *m = (char*)malloc(bytes);
if(m == NULL) cout << "cant allocate mem" << endl;
else cout << "ok" << endl;
activate.push_back(m);
}
else if(input[0] == 'a')
{
for(int x = 0; x < activate.size(); x++)
{
char *m;
m = activate[x];
for(unsigned x = 0; x < bytes; x++)
{
m[x] = 'a';
}
}
}
}
return 0;
}
我正在运行到有RAM 3GB的Linux虚拟机上此code。在使用HTOP工具监视系统资源的使用情况,我已经意识到,malloc的操作不会反映在资源。
I am running this code on a linux virtual machine that has 3Gb of ram. While monitoring the system resource usage using the htop tool, I have realized that the malloc operation is not reflected on the resources.
例如,当我输入'U'只有一次(即。分配的堆内存2GB),我没有看到的内存使用情况的2GB的HTOP增加。只有当我输入'A'(即初始化),我看到内存使用率增加。
For example when I input 'u' only once(i.e. allocate 2GB of heap memory), I don't see the memory usage increasing by 2GB in htop. It is only when I input 'a'(i.e. initialize), I see the memory usage increasing.
因此,我能的malloc更多的堆内存比存在。例如,我可以6GB的malloc(这是比我的RAM和交换内存更多),的malloc将允许它(即,NULL不是由malloc返回)。但是,当我尝试初始化分配的内存,我可以看到内存和交换内存填充,直到进程被杀死。
As a consequence, I am able to "malloc" more heap memory than there exists. For example, I can malloc 6GB(which is more than my ram and swap memory) and malloc would allow it(i.e. NULL is not returned by malloc). But when I try to initialize the allocated memory, I can see the memory and swap memory filling up till the process is killed.
- 我的问题:
1.Is这个系统内核的BUG?
1.Is this a kernel bug?
2,可为什么有人这种行为是允许我解释一下吗?
2.Can someone explain to me why this behavior is allowed?
推荐答案
这就是所谓的的内存过量使用的。您可以通过以root身份运行禁用它:
It is called memory overcommit. You can disable it by running as root:
echo 2 > /proc/sys/vm/overcommit_memory
和它不是一个内核的功能,我喜欢(所以我总是禁用它)。请参见的malloc(3)和的mmap(2)和的 PROC(5)
and it is not a kernel feature that I like (so I always disable it). See malloc(3) and mmap(2) and proc(5)
注: 0呼应
而不是回声2
的往往的 - 但没有始终在线的工作也。阅读文档(特别是 PROC
,我只是链接到手册页)。
NB: echo 0
instead of echo 2
often -but not always- works also. Read the docs (in particular proc
man page that I just linked to).
这篇关于分配更多的内存比使用有存在的malloc的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!