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

时光总嘲笑我的痴心妄想 提交于 2019-12-01 14:08:45

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

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.

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.

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