c++ - 使用 malloc 分配比现有内存更多的内存

标签 c++ c linux memory memory-management

此代码片段每次从 stdin 读取字母“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 RAM 的 Linux 虚拟机上运行此代码。在使用htop工具监控系统资源使用情况时,我发现malloc操作没有反射(reflect)在资源上。

例如,当我仅输入“u”一次(即分配2GB堆内存)时,我没有看到htop中的内存使用量增加了2GB。只有当我输入“a”(即初始化)时,我才会看到内存使用量增加。

因此,我能够“分配”比现有更多的堆内存。例如,我可以 malloc 6GB(这超过了我的 ram 和交换内存)并且 malloc 允许它(即 malloc 不返回 NULL)。但是当我尝试初始化分配的内存时,我可以看到内存和交换内存已填满,直到进程被终止。

-我的问题:

1.这是内核错误吗?

2.有人可以向我解释一下为什么允许这种行为吗?

最佳答案

它的名字是memory overcommit 。您可以通过以 root 身份运行来禁用它:

 echo 2 > /proc/sys/vm/overcommit_memory

这不是我喜欢的内核功能(所以我总是禁用它)。请参阅malloc(3)mmap(2)proc(5)

注意:echo 0 代替 echo 2 经常 - 但并非总是 - 也可以。阅读文档(特别是我刚刚链接到的 proc 手册页)。

关于c++ - 使用 malloc 分配比现有内存更多的内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58513685/

相关文章:

c# - HBITMAP *位图到 .net 位图

C++ 指针传递

c - C 中的字符串验证 : Trying to ask for a new string when the old one has an invalid character

c - 使用 mkfifo() 和 open() 的程序无法退出

c - 如何知道二进制整数是否代表负数?

linux - Slurm 无法运行多个 sbatch 任务

c++ - upper_bound() 给出了错误的输出

c++ - sqrt(x) 和 pow(x,0.5) 的区别

linux - 根据 Linux 内核中的 CONFIG 条目更改代码块

linux - 使用 UBUNTU 和 arm-linux-gnueabi-gcc 为 ARM linux 交叉编译 JamVM - 缺少 zlib