c++ - malloc 失败条件

标签 c++ c memory memory-management memory-leaks

我正在复习 c,重做一些旧的练习,并在运行此代码段时得到一些不寻常的结果(我知道它泄漏但想了解系统允许多少..)

#include <stdio.h>
#include <stdlib.h>

int main(int argc,char *argv[])
{
    void *page = 0; int index;
    index = 0;
    while(1)
    {
        page = malloc(1073741824); //1GB
        if(!page)break;
        ++index;
    }
    printf("memory failed at %d\n",index);
    return 0;
}

我实际上得到:

memory failed at 131070

这表明它认为它分配了 131070 x 1GB 内存(大量泄漏)

我之前知道 malloc 应该在消耗所有虚拟内存之前失败,当然如果我尝试在一个 block 中 malloc 20GB 就会失败。

我的设置: Ubuntu 10 8GB内存, <= 2Gb 交换空间, HD 1TB(这重要吗?)

任何人都知道它如何泄漏比我更多的内存

最佳答案

  • http://www.win.tue.nl/~aeb/linux/lk/lk-9.html

    Since 2.1.27 there are a sysctl VM_OVERCOMMIT_MEMORY and proc file /proc/sys/vm/overcommit_memory with values 1: do overcommit, and 0 (default): don't. Unfortunately, this does not allow you to tell the kernel to be more careful, it only allows you to tell the kernel to be less careful. With overcommit_memory set to 1 every malloc() will succeed. When set to 0 the old heuristics are used, the kernel still overcommits.

您可能还希望查看使用 mallinfo 进行检测:

最后一个链接:

In a way, Linux allocates memory the way an airline sells plane tickets. An airline will sell more tickets than they have actual seats, in the hopes that some of the passengers don't show up. Memory in Linux is managed in a similar way, but actually to a much more serious degree.

关于c++ - malloc 失败条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10420280/

相关文章:

c - C 中的动态双数组

c - 了解使用 SSE 指令进行矢量化

c - 在以下情况下,哪个更好? fread() 还是 mmap()?

c++ - 简单的效率问题 C++(内存分配)..也许一些碰撞检测有帮助?

c++ - Qt 请求从不触发 finished() 信号

java - JNI - java ArrayList 转换为 c++ std::string*

c - 套接字上的 select() (问题)

c - C中的堆栈执行

c# - 平台调用 #define 指令

c++ - 将 multimap<Key,Value> 转换为 vector <vector<Value>>