Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Program on Linux to exhaust memory

Tags:

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; } 
like image 416
Mark Avatar asked Dec 08 '09 08:12

Mark


People also ask

How do you get exhaust memory?

To simply exhaust memory, you don't need that at all. You can call new int(i) and throw away the returned pointer, and the memory will still be allocated. Remember also that your machine likely has virtual memory beyond the 2 GB physical RAM you have installed.

How does C memory work?

In C, dynamic memory is allocated from the heap using some standard library functions. The two key dynamic memory functions are malloc() and free(). The malloc() function takes a single parameter, which is the size of the requested memory area in bytes. It returns a pointer to the allocated memory.


2 Answers

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.

like image 191
nos Avatar answered Sep 30 '22 11:09

nos


Linux "over commits" memory. This means that physical memory is only given to a process when the process first tries to access it, not when the malloc is first executed. To disable this behavior, do the following (as root):

echo 2 > /proc/sys/vm/overcommit_memory 

Then try running your program.

like image 42
Zach Hirsch Avatar answered Sep 30 '22 10:09

Zach Hirsch