Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I declare a very large array in a class, C++

I am trying to write a class to store millions 3D coordinates data. At the first, I tried to use a 3D array to store those coordinates data.

#ifndef DUMPDATA_H
#define DUMPDATA_H
#define ATOMNUMBER 2121160
#include <string>
using namespace std;
class DumpData
{
public:
    DumpData(string filename);
    double m_atomCoords[ATOMNUMBER][3];
};
#endif // DUMPDATA_H

Then I compiled the program, but I got segfaults when I run the program in ubuntu 14.04 system (64 bit). So I changed the 3D array to vector by declaring:

vector < vector <double> > m_atomCoords;

Then the program worked. I am just wondering are there limitations of declaring very large arrays in a class?

like image 637
Xuhang Avatar asked Feb 12 '23 13:02

Xuhang


1 Answers

In general, the stack has a limited size.

This will likely cause a stack overflow:

int main() {
    DumpData x;
}

While these won't:

int main() {
    static DumpData x;
    std::unique_ptr<DumpData> y = std::make_unique<DumpData>();
}
like image 89
Bill Lynch Avatar answered Feb 15 '23 12:02

Bill Lynch