Allocation of memory more than 4 GB in a 64-bit system

I am running this code compiled on 64 bits vC ++ 2005, on Windows Server 2008 R2 with 32 GB. There is an access violation inside the for loop.

#include <iostream> using namespace std; int main(int argc, char* argv[]) { double *x = new double[536870912]; cout << "memory allocated" << endl; for(long int i = 0; i < 536870912; i++) { cout << i << endl; x[i] = 0; } delete [] x; return 0; } 

So, if there is no exception in the new double [536870912], why do I get an access violation when performing a job at a specific position of the array?

Another point worth mentioning is that this program was successfully tested on another computer.

+7
c ++ memory access-violation windows-server-2008-r2
source share
1 answer

This is probably one of the following issues:

  • long int is 32 bits: this means your maximum value is 2147483647 and sizeof (double) * 536870912> = 2147483647. (I really don't know if that makes sense. It probably depends on how the compiler works)
  • Your selection does not work.

I suggest you test the following code:

 #include<conio.h> #include <iostream> using namespace std; #define MYTYPE unsigned long long int main(int argc, char* argv[]) { // Test compiling mode if (sizeof(void*) == 8) cout << "Compiling 64-bits" << endl; else cout << "Compiling 32-bits" << endl; // Test the size of mytype cout << "Sizeof:" << sizeof(MYTYPE) << endl; MYTYPE len; // Get the number of <<doubles>> to allocate cout << "How many doubles do you want?" << endl; cin >> len; double *x = new (std::nothrow) double[len]; // Test allocation if (NULL==x) { cout << "unable to allocate" << endl; return 0; } cout << "memory allocated" << endl; // Set all values to 0 for(MYTYPE i = 0; i < len; i++) { if (i%100000==0) cout << i << endl; x[i] = 0; } // Wait before release, to test memory usage cout << "Press <Enter> key to continue..."; getch(); // Free memory. delete [] x; } 

Editing: using this code, I just allocated one block of 9 GB.

+3
source share

All Articles