I'm trying to write a c program to test how much memory is on my system. I'm planning to run it under various different conditions:
- With swap enabled
- With swap disabled and overcommit (/proc/sys/vm/overcommit_memory) set to false
- With swap disabled and overcommit (/proc/sys/vm/overcommit_memory) set to true
- Inside a virtual machine running on the system
I am doing this to learn more about how memory allocation behaves at the limits of the system's real and virtual memory.
I'm running this on a machine with 4GB RAM and 8GB Swap.
What I have currently is something like this:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int *ptr;
int mb = 1048576;
long long int i;
for (i = 0; i < 1000000000000; i++)
{
printf("Trying to allocate %lld MBytes\n", i * 10 * sizeof(int) );
ptr = (int*) calloc(10 * mb, sizeof(int));
if ( ptr == 0 ) {
// clean up
free(ptr);
printf("Ran out of memory\n");
return 1;
}
}
}
I was hoping that this would continue to allocate blocks of 40mb (sizeof(int) is 4 on my system). Calloc would initialize the memory to zero. When no more memory was available, it would terminate the program and free up the memory.
When I run it, it continues to run beyond the limits of my memory. It finally died while printing the line: "Trying to allocate 5707960 MBytes." (Indicating almost 6000 GB of memory.)
Can anybody figure out where I'm going wrong.
Thanks @Blank Xavier for pointing out that the page file size should be considered when allocating this way.
I modified the code as follows:
int main(void)
{
int *ptr;
int mb = 1048576;
int pg_sz = 4096;
long long int i;
for (i = 0; i < 1000000000000; i++)
{
printf("Trying to allocate %lld MBytes\n", i * pg_sz * sizeof(int) / mb );
ptr = (int*) calloc(pg_sz, sizeof(int));
if ( ptr == 0 ) {
// clean up
free(ptr);
printf("Ran out of memory\n");
return 1;
}
}
}
And now it bombs out printing:
"Trying to allocate 11800 MBytes"
which is what I expect with 4GB Ram and 8GB swap. By the way, it prints much more slowing after 4GB since it is swapping to disk.