title: Malloc, Calloc for testing the limits of my memory
body: <p>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:</p>
  
  <ol>
  <li>With swap enabled</li>
  <li>With swap disabled and overcommit (/proc/sys/vm/overcommit_memory) set to false</li>
  <li>With swap disabled and overcommit (/proc/sys/vm/overcommit_memory) set to true</li>
  <li>Inside a virtual machine running on the system</li>
  </ol>
  
  <p>I am doing this to learn more about how memory allocation behaves at the limits of the system's real and virtual memory.</p>
  
  <p>I'm running this on a machine with 4GB RAM and 8GB Swap.</p>
  
  <p>What I have currently is something like this:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  int main(void)
  {
      int *ptr;
      int mb = 1048576;
      long long int i;
  
      for (i = 0; i &lt; 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;
          }
      }
  }
  </code></pre>
  
  <p>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. </p>
  
  <p>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.)</p>
  
  <p>Can anybody figure out where I'm going wrong.</p>
  
  <p>Thanks @Blank Xavier for pointing out that the page file size should be considered when allocating this way.</p>
  
  <p>I modified the code as follows:</p>
  
  <pre><code>int main(void)
  {
      int *ptr;
      int mb = 1048576;
      int pg_sz = 4096;
  
      long long int i;
  
      for (i = 0; i &lt; 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;
          }
      }
  }
  </code></pre>
  
  <p>And now it bombs out printing:</p>
  
  <p>"Trying to allocate 11800 MBytes"</p>
  
  <p>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.</p>