Sunday, April 20, 2008

What do You expect from the following code:

#include stdio.h
#include stdlib.h


int main(void)
{
int *p;
while(1)
p = malloc(sizeof(int));
return 0;
}


Consume all memory... huh! No! It won't. If You are in doubt; copy, paste compile and execute before reading further.

Now try the following code:


#include stdio.h
#include stdlib.h


int main(void)
{
int *p;
while(1) {
p = malloc(sizeof(int));
*p = 0;
}
return 0;
}


Now be careful. Don't copy, paste compile and execute, close all important applications and save Your data.

I executed the above code with a system information application open which gives info about current memory usage. Initially the system RAM was all consumed, then the hard disk showed the activity, which was OS trying to swap as much data to disk as possible. When even all the swap is used up the process is killed. Meanwhile a few applications like Firefox were also aborted.

The aftereffect was that most of the physical RAM was almost free. That's really wonderful. Now before trying any new game I just run my little C code and get the maximum out of my PC