malloc失败条件 [英] malloc conditions for failure

查看:105
本文介绍了malloc失败条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在刷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;
}

我实际上正在得到:

内存在131070处失败

这表明它认为分配了131070 x 1GB内存(慷慨地泄漏了)

我以前曾了解过malloc在消耗所有虚拟内存之前应该会失败,并且可以肯定的是,如果我尝试在一个块中使用20 GB的内存,这会失败.

我的设置: Ubuntu 10 8Gb ram, < = 2Gb交换, HD 1TB(这个有问题吗?)

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

解决方案

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

    从2.1.27开始,存在一个sysctl VM_OVERCOMMIT_MEMORY和proc文件 /proc/sys/vm/overcommit_memory的值1:执行过量使用,0 (默认):不.不幸的是,这不允许您告诉 内核要更加小心,它只允许您告诉内核 不太小心.在overcommit_memory设置为1的情况下,每个malloc()将 成功.当设置为0时,使用旧的启发式算法,内核仍然 过量使用.

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

最后一个链接:

在某种程度上,Linux像航空公司出售飞机的方式分配内存 票.一家航空公司将售出比实际更多的机票 座位,希望一些乘客不出现.记忆 Linux中的管理方式类似,但实际上要多得多 认真的学位.

I'm brushing up on c, redoing some old exercizes and getting some unusual results when I run this snippet (I know its leaking but want to find out how much the system allows..)

#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;
}

I'm actually getting:

memory failed at 131070

this indicates it thinks its allocated 131070 x 1GB memory (leaking generously)

I had previously understood malloc should fail before consuming all virtual memory and certainly if I try and malloc 20GB in one block this fails.

My setup: ubuntu 10 8Gb ram, <= 2Gb swap, HD 1TB (does this matter?)

anyone have an idea how it can leak more memory than I have

解决方案

  • 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.

You might also wish to look at instrumenting with mallinfo:

One final link:

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.

这篇关于malloc失败条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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