【发布时间】:2013-11-14 01:44:27
【问题描述】:
这段代码 sn-p 将在每次从标准输入读取字母“u”时分配 2Gb,并在读取“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;
}
我在具有 3Gb 内存的 linux 虚拟机上运行此代码。在使用 htop 工具监控系统资源使用情况时,我意识到 malloc 操作并没有反映在资源上。
例如,当我只输入 'u' 一次(即分配 2GB 堆内存)时,我看不到 htop 中的内存使用量增加了 2GB。只有当我输入“a”(即初始化)时,我才看到内存使用量增加。
因此,我能够“malloc”比现有更多的堆内存。例如,我可以 malloc 6GB(这比我的 ram 和交换内存多)并且 malloc 会允许它(即 malloc 不返回 NULL)。但是当我尝试初始化分配的内存时,我可以看到内存和交换内存已满,直到进程被杀死。
-我的问题:
1.这是内核错误吗?
2.有人可以向我解释为什么允许这种行为吗?
【问题讨论】:
-
顺便说一句,您对
gets()的调用会导致缓冲区溢出。解决办法就是,扔掉它。 -
你有undefined behavior。您不能确定未初始化的
input[0]在main的开头不是q,您很幸运。使用g++ -Wall编译。
标签: c++ c linux memory memory-management