Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to exhaust memory?

It might look silly, but I'm kind of confused about this now. Why this program won't consume all the memory? For example: I have the following program running in a Linux(2G RAM) terminal,

  #include <iostream>
  #include <cmath>
  using namespace std;

  int main()
  {
     cout<<sizeof(int*)<<endl;
     for(int i=0; i<pow(2.0,30.0);i++)
       {
         new int(i);
       }
    return 1;
  }

1) I confirmed the int size in this machine is 4 bytes, then for 2GB ram, it can only hold 2^30/2^2=2^28

2) following the logic above, how could you change the program actually consume all the 2GB memory?

Added: I just want to make sure I understand it correctly theoreticaly. If there is no virtual memory or os optimization etc.., 2GBRAM only could hold 2^28 int, is that right? In that case, the above program will consume all memory? Do you know how I could turn off the virtual memory/swap memory features etc.. in a linux?

Thanks!

like image 319
WilliamLou Avatar asked Dec 16 '22 12:12

WilliamLou


1 Answers

Because of virtual addressing, you can allocate more memory than you actually have in terms of RAM. The OS will automatically page out memory (to the hard drive) that you're not using. In this way, your RAM serves as a large cache to the hard disk's swap file, which represents the actual memory of your system.

Your actual limit is the address space of a pointer, which unless you're compiling for (and running on) a 64-bit platform is 32-bits. So you can allocate 4GB of space.

like image 55
Nicol Bolas Avatar answered Dec 29 '22 18:12

Nicol Bolas