本文介绍了在构造函数中为什么使用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.

我的构造函数如下:

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旗舰版:当试图启动一个使用这个类的程序,它有一个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.

这一切的谜团是,在我的previous版本,其中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?

推荐答案

所以你presumably做到这一点在你的主(或其他地方)

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

这篇关于在构造函数中为什么使用FREAD时,我的程序崩溃?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 09:55