Why does my program crash when using fread in the

2019-02-20 18:59发布

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?

3条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-02-20 19:04

This declaration in your class:

int myarray[45000000];

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.

查看更多
迷人小祖宗
3楼-- · 2019-02-20 19:05

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 your Test 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.

查看更多
甜甜的少女心
4楼-- · 2019-02-20 19:11

so you presumably do this in your main (or anywhere else)

int main ()
{
  Test t; // Hello StackOverflow
}

What you need is allocate it on the heap:

int main ()
{
  Test* t = new Test;
  delete t;
}

It didn't crash with static variable because static variables are NOT allocated on the stack

查看更多
登录 后发表回答