gpt4 book ai didi

c++ - malloc 失败条件

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:56:05 25 4
gpt4 key购买 nike

我正在复习 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 108GB内存,<= 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com