Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory Leak Using malloc fails

Tags:

c

linux

memory

I am writing a program to leak memory( main memory ) to test how the system behaves with low system memory and swap memory. We are using the following loop which runs periodically and leaks memory

main(int argc, char* argv[] )  
{
   int arg_mem = argv[1];

        while(1)
        {
          u_int_ptr =(unsigned int*)  malloc(arg_mem * 1024 * 1024);

        if( u_int_ptr == NULL )
           printf("\n leakyapp Daemon FAILED due to insufficient available memory....");

          sleep( arg_time );
        }

}

Above loop runs for sometime and prints the message "leakyapp Daemon FAILED due to insufficient available memory...." . But when I run the command "free" I can see that running this program has no effect either on Main memory or Swap.

Am I doing something wrong ?

like image 395
Sirish Avatar asked Aug 16 '26 06:08

Sirish


2 Answers

Physical memory is not committed to your allocations until you actually write into it.

If you have a kernel version after 2.6.23, use mmap() with the MAP_POPULATE flag instead of malloc():

u_int_ptr = mmap(NULL, arg_mem * 1024 * 1024, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_POPULATE, -1, 0);

if (u_int_ptr == MAP_FAILED)
    /* ... */

If you have an older kernel, you'll have to touch each page in the allocation.

like image 141
caf Avatar answered Aug 18 '26 22:08

caf


There might be some sort of copy-on-write optimization. I would suggest actually writing something to the memory you are allocating.

like image 42
Karl Bielefeldt Avatar answered Aug 18 '26 21:08

Karl Bielefeldt