gpt4 book ai didi

c++ - ifstream fileOpen 导致程序到 'terminate in an unusual way'

转载 作者:行者123 更新时间:2023-11-28 07:32:05 25 4
gpt4 key购买 nike

在行:std::ifstream fileOpen(file.c_str()); 在下面的函数中程序崩溃并给我这个错误:

This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information.


Process exited with return value 3

然而,在 Debug模式下,整个程序运行,但在主函数的 return 0 语句中我得到

Program received signal SIGTRAP, Trace/breakpoint trap.

我在 Windows 7 上使用 Orwell Dev/C++。据我所知,第一个问题是抛出但未捕获的异常(我还没有自学异常,所以我不知道该怎么做,但我可以阅读)并且它可能会破坏堆栈。后一个错误我无法获得更多具体信息。谁能指出解决方案的方向?哦,还有,该函数在第四次崩溃之前被调用了三次。

//Get a line of data from a file
std::string getData( std::string file, int line )
{
std::string data;
std::ifstream fileOpen(file.c_str());

if (fileOpen.is_open())
{
if( fileOpen.good() )
{
for( int lineno = 0; getline(fileOpen,data) && lineno < line; lineno ++ )
{
if( lineno != line )
{
data = "";
}
}
}

fileOpen.close();
}

return data;
}

//Parse comma delimited string into a vector
void parseData( std::vector<double> &temp, std::string data )
{
std::istringstream ss(data);
std::string token;

while(std::getline(ss, token, ','))
{
temp.push_back(atoi(token.c_str()));
}
}

这些是通过这样的代码调用的:

std::string instData = getData( levelName+".dat", 2 );

if( instData != "" )
{
parseData( temp, instData );
instances.resize(temp.size() / 4);
j = 0;

for( int i = 0; i < temp.size(); i += 4 )
{
instances[ j ].type = temp[ i ];
instances[ j ].xPos = temp[ i + 1 ];
instances[ j ].yPos = temp[ i + 2 ];
instances[ j ].zIndex = temp[ i + 3 ];
j ++;
}

temp.clear();
}

此代码本身是一个函数的一部分,该函数旨在用指定文件中的数据填充各种 vector 。不过,其中的其余代码与上面的基本相同。

最佳答案

我可以清楚地看到这里的问题:

instances[ j ].xPos   = temp[ i + 1 ];
instances[ j ].yPos = temp[ i + 2 ];
instances[ j ].zIndex = temp[ i + 3 ];

i == temp.size() - 3 时,最后一条语句将访问内存区域 1,超出为 temp 分配的内存末尾,导致 Undefined Behavior .发生这种情况后,您的程序就进入了无效状态。

在打开文件的那一行出现错误可能只是未定义行为的影响之一。作为测试,删除上面三行并查看是否发生任何运行时错误。

关于c++ - ifstream fileOpen 导致程序到 'terminate in an unusual way',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17456620/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com