I have a small program, written in C++ that contains a class with a large array. The class looks like this:
class Test
{
public:
Test();
...
private:
int myarray[45000000];
};
Now, this array is read in from a file. I would like to do this with the constructor directly, instead of bothering to call any extra functions. The array only needs to be read in once, and afterwards will not change anymore. It has the exact size specified.
My constructor looks like this:
Test()
{
memset(myarray, 0, sizeof(myarray));
FILE* fstr = fopen("myfile.dat", "rb");
size_t success= fread(myarray, sizeof(myarray), 1, fstr);
fclose(fstr);
}
Using Visual Studio 2012 Ultimate: When trying to start a program that uses this class, it crashes with an "APPCRASH" as soon as the class is created, and when trying to debug it (which I have next to no knowledge of), tells me that the error is a Stack overflow.
The mystery of this all is that in my previous version, where myarray was a static variable, and I had to call a static function to set it, everything went just fine. But trying to convert this to a constructor, try as I might, all my attempts fail.
So what am I doing wrong here?
This declaration in your class:
is trying to allocate 45,000,000 * 4 bytes per int (assuming 32-bit) = 180MB of memory. No way your stack is going to support that. You need to redesign the app to change how you load your file.
Even if your
int
were the minimum size of 2 bytes, your array would use about 86MB of memory. A typical maximum stack size is 1MB. If the storage for yourTest
object is allocated on the stack, you'll easily overflow. You'll need to either dynamically allocate your array or not load all of it into memory at once. Better yet, use a standard container that uses dynamic allocation for its elements, like `std::vector.so you presumably do this in your main (or anywhere else)
What you need is allocate it on the heap:
It didn't crash with static variable because static variables are NOT allocated on the stack