C Program on Linux to exhaust memory

前端 未结 10 641
孤独总比滥情好
孤独总比滥情好 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:29

    If all you need is to stress the system, then there is stress tool, which does exactly what you want. It's available as a package for most distros.

    0 讨论(0)
  • 2020-12-24 03:30

    I was bored once and did this. Got this to eat up all memory and needed to force a reboot to get it working again.

    #include <stdlib.h>
    #include <unistd.h>
    
    int main(int argc, char** argv)
    {
        while(1)
        {
            malloc(1024 * 4);
            fork();
        }
    }
    
    0 讨论(0)
  • 2020-12-24 03:32

    Linux uses, by default, what I like to call "opportunistic allocation". This is based on the observation that a number of real programs allocate more memory than they actually use. Linux uses this to fit a bit more stuff into memory: it only allocates a memory page when it is used, not when it's allocated with malloc (or mmap or sbrk).

    You may have more success if you do something like this inside your loop:

    memset(malloc(1024*1024L), 'w', 1024*1024L);
    
    0 讨论(0)
  • 2020-12-24 03:32

    In my machine, with an appropriate gb value, the following code used 100% of the memory, and even got memory into the swap. You can see that you need to write only one byte in each page: memset(m, 0, 1);, If you change the page size: #define PAGE_SZ (1<<12) to a bigger page size: #define PAGE_SZ (1<<13) then you won't be writing to all the pages you allocated, thus you can see in top that the memory consumption of the program goes down.

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    #define PAGE_SZ (1<<12)
    
    int main() {
        int i;
        int gb = 2; // memory to consume in GB
    
        for (i = 0; i < ((unsigned long)gb<<30)/PAGE_SZ ; ++i) {
            void *m = malloc(PAGE_SZ);
            if (!m)
                break;
            memset(m, 0, 1);
        }
        printf("allocated %lu MB\n", ((unsigned long)i*PAGE_SZ)>>20);
        getchar();
        return 0;
    }
    
    0 讨论(0)
提交回复
热议问题