I play to understand how much memory can be allocated. Initially, I thought that the maximum memory that can be allocated is equal to physical memory (RAM). I tested my RAM on Ubuntu 12.04 by running a command as shown below:
~$ free -b total used free shared buffers cached Mem: 3170848768 2526740480 644108288 0 265547776 1360060416 -/+ buffers/cache: 901132288 2269716480 Swap: 2428497920 0 2428497920
As shown above, the general physical memory is 3Gig (3170848768 bytes), of which only 644108288 bytes are free, so I suggested that I can only maximize this large memory allocation. I tested it by writing a small program with only two lines below:
char * p1 = new char[644108290] ; delete p1;
Since the code works fine, it means that it has successfully allocated memory. I also tried to allocate a memory larger than the available physical free memory, but it did not produce any error. Then to the question
the maximum memory that malloc can allocate
I thought he should use virtual memory. So I tested the code for free swap memory, and it worked too.
char * p1 = new char[2428497920] ; delete p1;
I tried to allocate a free swap plus free RAM bytes of memory
char * p1 = new char[3072606208] ; delete p1;
But this time code did not throw a bad_alloc exception. Why this code did not work this time.
Now I allocated memory at compile time in a new program, as shown below:
char p[3072606208] ; char p2[4072606208] ; char p3[5072606208]; cout<<"Size of array p = " <<sizeof p <<endl; cout<<"Size of array p2 = " <<sizeof p2<<endl; cout<<"Size of array p2 = " <<sizeof p3;
Output shows
Size of array p = 3072606208 Size of array p1 = 4072606208 Size of array p2 = 777638912
Could you help me understand what is happening here. Why is this allowed to allocate memory at compile time, but not dynamically. When compilation time is allocated, how p and p1 could allocate more memory than swap plus free RAM. Where p2 failed. How exactly does it work. This is some kind of undefined behavior or specific behavior. Thank you for your help. I am using Ubuntu 12.04 and gcc 4.6.3.