I am working with VC++ for some months now. I have never come across 'Stack Overflow' error until today when I try to pass a structure to function.
This is my code:
int bReadFileData(string sFile, struct FILE_DATA *File_Data);
const int MAX_CRASH_FILE_SIZE = 100000;
struct FILE_DATA
{
int SIZE;
int GOOD[MAX_CRASH_FILE_SIZE];
int BAD[MAX_CRASH_FILE_SIZE];
};
int bReadFileData(string sFile, struct FILE_DATA *File_Data)
{
File_Data->SIZE = 0;
if(PathFileExists(Convert.StringToCstring(sFile)) == 1)
{
string sLine = "";
int iLine = 0;
std::ifstream File(sFile);
while(getline(File, sLine))
{
if(sLine.find(":") != std::string::npos)
{
File_Data->CRASH_VALUES[iLine] = sLine.substr(0, sLine.find(":"));
File_Data->CRASH_VALUES[iLine] = sLine.substr(sLine.find(":") + 1, sLine.length());
}
else
{
File_Data->CRASH_VALUES[iLine] = (sLine);
}
iLine++;
}
File_Data->SIZE = iLine;
}
return 1;
}
`
From main function I am calling below method.
void ReadFiles()
{
FILE_DATA Files[3];
bReadFileData("C:\\Test1.txt", &Files[0]);
bReadFileData("C:\\Test2.txt", &Files[1]);
bReadFileData("C:\\Test3.txt", &Files[2]);
}
Is there any thing wrong in this code? Why stack overflow error is thrown(as soon as it enter ReadFiles()?
Why stack overflow error is thrown(as soon as it enter ReadFiles()?
That's because FILE_DATA[3] allocates too much bytes for stack memory. The size of stack memory is around 1Mb by default, while size of FILE_DATA[3] is around 2.4Mb (~ 800,000 x 3 bytes).
If you use the struct with large size, try to use heap memory as follows:
void ReadFiles()
{
FILE_DATA* Files = new FILE_DATA[3];
bReadFileData("C:\\Test1.txt", &Files[0]);
bReadFileData("C:\\Test2.txt", &Files[1]);
bReadFileData("C:\\Test3.txt", &Files[2]);
delete [] Files;
Files = nullptr;
}