为什么我的程序在构造函数中使用 fread 时会崩溃?

2022-01-12 00:00:00 arrays crash c++ fread

我有一个小程序,用 C++ 编写,其中包含一个带有大数组的类.该类如下所示:

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);
}

使用 Visual Studio 2012 Ultimate:尝试启动使用此类的程序时,它会在创建类后立即崩溃并显示APPCRASH",并且在尝试调试它时(我几乎不知道),告诉我错误是堆栈溢出.

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.

这一切的奥秘在于,在我以前的版本中,myarray 是一个静态变量,我必须调用一个静态函数来设置它,一切都很顺利.但是尝试将其转换为构造函数,尽我所能,我所有的尝试都失败了.

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?

推荐答案

所以你大概在你的 main(或其他任何地方)这样做

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

相关文章