Linux下C程序耗尽内存 [英] C Program on Linux to exhaust memory

查看:317
本文介绍了Linux下C程序耗尽内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个程序来消耗所有可用内存,了解的结果。我听说linux的启动查杀过程中,一旦无法分配内存。

谁能帮我这样一个程序。

我写了下面的,但记忆似乎并没有得到疲惫:

 的#include<&stdlib.h中GT;诠释的main()
{
        而(1)
        {
                的malloc(1024 * 1024);
        }
        返回0;
}


解决方案

您应该写入分配的块。如果你只是问内存,Linux的可能只是伸手内存预约,但没有将被分配到内存访问。

  INT的main()
{
        而(1)
        {
                无效* M =的malloc(1024 * 1024);
                memset的(男,0,1024 * 1024);
        }
        返回0;
}

您真的只需要在每个页面上(通常在x86上4096字节)虽然写1个字节。

I would like to write a program to consume all the memory available to understand the outcome. I've heard that linux starts killing the processes once it is unable to allocate the memory.

Can anyone help me with such a program.

I have written the following, but the memory doesn't seem to get exhausted:

#include <stdlib.h>

int main()
{
        while(1)
        {
                malloc(1024*1024);
        }
        return 0;
}

解决方案

You should write to the allocated blocks. If you just ask for memory, linux might just hand out a reservation for memory, but nothing will be allocated until the memory is accessed.

int main()
{
        while(1)
        {
                void *m = malloc(1024*1024);
                memset(m,0,1024*1024);
        }
        return 0;
}

You really only need to write 1 byte on every page (4096 bytes on x86 normally) though.

这篇关于Linux下C程序耗尽内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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