Com*_*erd 1 c++ memory stack-overflow
我不明白为什么当我进入main函数时我立即得到堆栈溢出.我应该从文本文件中读取并进行一些处理.有人可以向我解释原因,并建议如何解决它?
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <fstream>
#include <iomanip>
using namespace std;
const int MAX=100;
enum countrytype{S,F};
struct dob
{
int day;
int month;
int year;
};
struct Local
{
char country[MAX];
char gender[MAX];
char name[MAX];
dob birthday;
int noofmod;
char mod[MAX][MAX];
int mark[MAX];
};
struct Foreign
{
char country[MAX];
char gender[MAX];
char name[MAX];
dob birthday;
int noofmod;
char mod[MAX][MAX];
int mark[MAX];
};
union Student
{
Local localstudent;
Foreign foreignstudent;
};
struct UOWstudent
{
countrytype ct;
Student st;
};
void readfile(ifstream &read,UOWstudent noofstudent[MAX]);
int main()
{
UOWstudent noofstudent[MAX];
ifstream read;
readfile(read,noofstudent);
cout<<endl
<<noofstudent[0].st.foreignstudent.country
<<endl
<<noofstudent[0].st.foreignstudent.gender
<<endl
<<noofstudent[0].st.foreignstudent.name;
system("PAUSE");
}
void readfile(ifstream &read, UOWstudent noofstudent[MAX])
{
int i=0;
char country;
char filename[MAX];
cin>>filename;
read.open(filename);
read>>country;
/*if (country =='F')
{
read.getline(noofstudent[i].st.foreignstudent.country,MAX);
read>>noofstudent[i].st.foreignstudent.gender;
read.getline(noofstudent[i].st.foreignstudent.name,MAX);
}
else
read.getline(noofstudent[i].st.foreignstudent.country,MAX);*/
}
Run Code Online (Sandbox Code Playgroud)
这是我的文本文件
F South Korea
Male Psy Park Jae Sang
31 - 12 -1977
3 CSCI114 55 CSCI103 44 GangNam
Run Code Online (Sandbox Code Playgroud)
简单地说,您的代码是在堆栈上分配所有存储,并且您分配的数量超过了允许的限制.
看看你超越极限的原因可能更有用.
第一行main()
是在堆栈上分配100(MAX = 100)个学生的数组:
UOWstudent noofstudent[MAX];
Run Code Online (Sandbox Code Playgroud)
有多大UOWstudent
?您可以通过查看每个字段来解决这个问题:
struct UOWstudent
{
countrytype ct; // enum. let's assume 4 bytes. (32-bit executable)
Student st; // ???
};
Run Code Online (Sandbox Code Playgroud)
学生有多大?
union Student
{
Local localstudent;
Foreign foreignstudent;
};
Run Code Online (Sandbox Code Playgroud)
这是一个本地或外国的大小,所以让我们看一个.我们需要对char的大小做另一个假设.我们假设1 byte
(8位字符):
struct Local
{
char country[MAX]; // 100 bytes
char gender[MAX]; // 100 bytes
char name[MAX]; // 100 bytes
dob birthday; // 3 ints or 12 bytes (32-bit assumption again)
int noofmod; // 4 bytes
char mod[MAX][MAX]; // 10,000 bytes
int mark[MAX]; // 400 bytes
}; // total: 10,716 bytes
Run Code Online (Sandbox Code Playgroud)
因此,main()的第一行尝试在堆栈上分配(10,716 + 4)x 100 = 1,072,000个字节.我对编译器设置的char和int的大小做了最保守的假设,它们可能更高.如果堆栈限制确实是1兆字节(1,048,576字节),则此初始分配超过限制.
您可以使用C的sizeof运算符来获取有关类型实际大小的信息. 请参阅此stackoverflow答案,讨论在堆上而不是堆栈上分配数组,这是解决问题的一个很好的步骤. (UOWstudent ==滑铁卢大学的学生?)
归档时间: |
|
查看次数: |
158 次 |
最近记录: |