Why does my program crash when using fread in the constructor?

你离开我真会死。 提交于 2019-12-30 14:38:35

问题


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?


回答1:


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




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/15136992/why-does-my-program-crash-when-using-fread-in-the-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!