I am trying to create an array of doubles with 3 million random elements:
#include <iostream>
#include <cstdlib>
#include <random>
#include <ctime>
using namespace std;
int main(int argc, const char * argv[]) {
// generating random numbers
mt19937 rng_engine(0); // seed = 0
uniform_real_distribution<double> dist2(0,10);
clock_t begin = clock();
// create a random 2d array 1 million x 3
double coords[1000000][3];
for (int i=0; i<1000000; i++) {
for (int j= 0; j<3; j++) {
coords[i][j] = dist2(rng_engine);
//cout << "i = " << i << ", j = " << j << ", val = " << coords[i][j] << endl;
}
}
clock_t end = clock();
double elapsed = double(end - begin) / CLOCKS_PER_SEC;
cout << "elapsed: " << elapsed << endl;
return 0;
}
When I try to run this in Xcode, I get EXC_BAD_ACCESS (code=2, address=0x7fff5e51bf9c)
. I tried to compile it and run it in the command line, which gave Segmentation fault: 11
. When I change the array size to [100000][3]
, making the number of elements 300,000, the code runs. What I don't understand is why is it a problem to have 3 million doubles. Wouldn't the array size be 24 MB? (8 bytes * 3,000,000 = 24 MB) What am I missing?