title: Maximum memory that can be allocated dynamically and at compile time in c++
body: <p>I am playing around to understand how much memory can be allocated. Initially I thought that the maximum memory which can be allocated is equal to Physical memory (RAM). I checked my RAM on Ubuntu 12.04 by running the command as shown below:</p>
  
  <pre><code>~$ free -b
               total       used       free     shared    buffers     cached
  Mem:    3170848768 2526740480  644108288          0  265547776 1360060416
  -/+ buffers/cache:  901132288 2269716480
  Swap:   2428497920          0 2428497920
  </code></pre>
  
  <p>As shown above,total physical memory is 3Gig (3170848768 bytes) out of which only 644108288 bytes is free, so I assumed I can at max allocate only this much memory. I tested it by writing the small program with only two lines below:</p>
  
  <pre><code>char * p1 = new char[644108290] ;
  delete p1;
  </code></pre>
  
  <p>Since code ran perfectly , it means it allocated memory successfully. Also I tried to allocate the memory greater than the available physical free memory still it did not throw any error. Then per question </p>
  
  <p><a href="https://stackoverflow.com/questions/2798330/maximum-memory-which-malloc-can-allocate">maximum memory which malloc can allocate</a></p>
  
  <p>I thought it must be using the virtual memory.So I tested the code for free swap memory and it also worked.</p>
  
  <pre><code>char * p1 = new char[2428497920] ;
  delete p1;
  </code></pre>
  
  <p>The I tried to allocate the free swap plus free RAM bytes of memory</p>
  
  <pre><code>char * p1 = new char[3072606208] ;
  delete p1;
  </code></pre>
  
  <p>But this time code failed throwing the <code>bad_alloc</code> exception.Why the code didn't work this time.</p>
  
  <p>Now I allocated the memory at compile time in a new program as shown below:</p>
  
  <pre><code>char p[3072606208] ;
  char p2[4072606208] ;
  char p3[5072606208];
  cout&lt;&lt;"Size of array p = " &lt;&lt;sizeof p &lt;&lt;endl;
  cout&lt;&lt;"Size of array p2 = " &lt;&lt;sizeof p2&lt;&lt;endl;
  cout&lt;&lt;"Size of array p2 = " &lt;&lt;sizeof p3;
  </code></pre>
  
  <p>The out put shows </p>
  
  <pre><code>Size of array p = 3072606208
  Size of array p1 = 4072606208
  Size of array p2 = 777638912
  </code></pre>
  
  <p>Could you please help me understand what is happening here. Why did it allowed the memory to be allocated at the compile time but not at dynamically.
  When allocated compile time how come <code>p</code> and <code>p1</code> were able to allocate memory greater than swap plus free RAM memory. Where as <code>p2</code> failed.
  How exactly is this working. Is this some undefined behaviour or os specific behaviour. Thanks for your help. I am using Ubuntu 12.04 and gcc 4.6.3.</p>