Why does my program crash when using fread in the constructor?(为什么我的程序在构造函数中使用 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
这篇关于为什么我的程序在构造函数中使用 fread 时会崩溃?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么我的程序在构造函数中使用 fread 时会崩溃?


基础教程推荐
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 我有静态或动态 boost 库吗? 2021-01-01