Search code examples
c++stdarray

Change of array dimensions causes crash c++


I need some big arrays in my program, and I was testing it with arrays of size=16*16*12*12.

Then I changed my program to run with size=64*64*12*12 and it crashed before even going to main.

Is the problem that such arrays take too much memory? I tried to run the code on my laptop and then also on some more powerful desktop, in both cases it crashed immediately with the bigger array, and works for the smaller array. The array size is controlled by a const int that is declared in the beginning of the code. I use the

    std::array<double, (64*64*12*12)>.

Thanks in advance

Update: The smallest program I wrote that has the same problem is the following:

    #include <iostream>
    #include <array>
    using namespace std;
    //declare variables
    using std::array;
    const int size_q=2;
    const int qpoints=size_q*size_q*size_q;
    const int size_k=2;
    const int kpoints=size_k*size_k*size_k;
    const int branches=12;
    const int size_ph=kpoints*branches;
    const int size_Theta=size_ph*size_ph;
    array<double, size_Theta> f_ph(array<double,size_Theta>);


    int main(int argc, char const *argv[])
    {
    array<double, size_Theta> theta1;
    f_ph(theta1);
    cout <<"Done";
    return 0;
    }
    array<double, size_Theta> f_ph(array<double,size_Theta> theta1){
    for(int i=0;i<size_Theta;i++){
    theta1[i]=1.00;
    }
    return theta1;

**Update: Seems like it is indeed the memory, using std::vector the program runs smoothly **


Solution

  • You're most likely running out of memory on the automatic store ("stack").

    You can either use a vector:

    #include <vector>
    std::vector<double> arr(64*64*12*12);
    arr[0]; // access first element
    

    Or you can use a unique_ptr if you dont need the flexibility a vector offers:

    #include <memory>
    auto arr = std::make_unique<std::array<double, (64*64*12*12)>>();
    (*arr)[0]; // access first element