繁体   English   中英

不知道为什么我会出现堆栈溢出

[英]Don't know why I am getting a stack overflow

我不明白为什么进入主函数时会立即出现堆栈溢出。 我应该从一个文本文件中读取并进行一些处理。 有人可以向我解释原因并提出解决方法吗?

#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);*/




}

这是我的文字档

F South Korea
Male Psy Park Jae Sang
31 - 12 -1977
3 CSCI114 55 CSCI103 44 GangNam

简而言之,您的代码在堆栈上分配了所有存储空间,并且分配的空间超出了允许的限制。

查看为什么您超出限制可能更有用。

main()的第一行是在堆栈上分配100个(MAX = 100)个学生的数组:

UOWstudent noofstudent[MAX];

UOWstudentUOWstudent 您可以通过查看每个字段来弄清楚:

struct UOWstudent
{
    countrytype ct; // enum. let's assume 4 bytes. (32-bit executable)
    Student st;     // ???
};

一个学生多大?

union Student
{
    Local localstudent;
    Foreign foreignstudent;
};

它是本地或外国的大小,所以让我们来看一个。 我们需要对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

因此main()的第一行尝试在堆栈上分配(10,716 + 4)x 100 = 1,072,000字节。 而且我对编译器设置中char和int的大小做了最保守的假设,它们可能更高。 如果堆栈限制确实为一兆字节(1,048,576字节),则此初始分配将超过该限制。

您可以使用C的sizeof运算符获取有关类型的实际大小的信息。 请参考此stackoverflow答案,讨论在堆而不是堆栈上分配数组,这是解决问题的好一步。 (UOWstudent ==滑铁卢大学的学生吗?)

MAX定义为100(确实需要吗?),您有一堆char数组,长度为MAX个元素,甚至还有一个2D数组,这是巨大的。 因此,您的结构非常庞大,可能超出了最大堆栈大小-我认为Windows中的大小为1024Kb。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM