I am running the below code on Debian Linux kernel 2.6.26. I was watching the resource manager in Linux and noticed that this program does not free memory properly until its execution ends. I assumed it would return the memory after the free() and before the sleep() but that is not what I am seeing when I run this code. If you run it with parameters that exhaust your system's memory it even begins to use swap space which it also holds onto until the sleep ends and the program terminates. Does anyone know why Linux doesn't show this memory as being freed?
Code:
int block_size = 262144;
char* stuff = malloc(block_size);
int current = block_size;
int x;
printf("Growing..... \n");
for(x=0; x<100; x++)
{
stuff = realloc(stuff, current + block_size);
current += block_size;
memset(stuff, 'a', current);
}
printf("Shrinking..... \n");
for(x=0; x<100; x++)
{
stuff = realloc(stuff, current - block_size);
current -= block_size;
memset(stuff, 'b', current);
}
free(stuff);
printf("I am sleeping now. Did the memory free?\n");
sleep(10);