C Program on Linux to exhaust memory

前端 未结 10 691
孤独总比滥情好
孤独总比滥情好 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: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 
    #include 
    #include 
    
    #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;
    }
    

提交回复
热议问题