C Program on Linux to exhaust memory

前端 未结 10 709
孤独总比滥情好
孤独总比滥情好 2020-12-24 03:06

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 alloc

10条回答
  •  情书的邮戳
    2020-12-24 03:17

    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.

提交回复
热议问题