使用 malloc 分配比现有内存更多的内存 [英] Allocating more memory than there exists using malloc

查看:31
本文介绍了使用 malloc 分配比现有内存更多的内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这段代码每次从标准输入中读取字母 '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;
}

我在具有 3Gb 内存的 Linux 虚拟机上运行此代码.在使用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 的堆内存)时,我没有看到 htop 中的内存使用量增加了 2GB.只有当我输入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(这比我的 ram 和交换内存多)并且 malloc 会允许它(即 malloc 不返回 NULL).但是当我尝试初始化分配的内存时,我可以看到内存和交换内存被填满,直到进程被终止.

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.这是内核错误吗?

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)

注意:echo 0 而不是 echo 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屋!

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