我正在尝试解决一个算法问题,但我看到了奇怪的行为。每当我注释掉第一个 cout 语句时,因为它看起来相对良性并且仅用于测试目的,我的脚本不会运行。它会编译而不会出错,但是当我使用 txt 文件输入参数运行时它会崩溃。
但是,如果我在下面的脚本中保留 cout 语句,它可以正常运行,没有任何问题。我不确定为什么会这样。在注释掉看似非必要的 cout 语句时,脚本再次运行但未达到预期效果。我在这里缺少什么?
测试输入文件
5
9 6
4 6 8
0 7 1 5
int main(int argc, char *argv[])
{
ifstream stream(argv[1]);
string line;
while (getline(stream, line))
{
cout<<line<<" String representation."<<endl; // Why do i need to keep this to prevent segfault / AppCrash (windows)?
vector<long int> numbers = string_to_ints(line);
for (int i =0; i < numbers.size(); i++)
{
cout<<numbers.at(i)<<" ";
}
cout<<" number representation."<<endl;
}
return 0;
}
下面的 string_to_ints() 声明
vector<long int> string_to_ints(string input) // takes string input and produces a list of ints
{
char* buffer;
stringstream ss(input);
vector<long int> tokens;
while (ss >> buffer)
{
tokens.push_back(atol(buffer)); // creates a vector of ints
}
return tokens;
}
我使用的是 gcc 4.8.1 版
最佳答案
问题是您永远不会在 string_to_ints
中为 buffer
分配内存。由于这是未定义的行为,任何都可能发生,包括在 cout 到位时似乎工作,而在 cout 被删除时不工作。
最简单的解决方案是使用 std::string
而不是 char*
作为缓冲区。然后你就避免了自己的内存管理。
关于c++ - C++ 中的奇怪行为,需要 cout 语句来防止应用程序崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27708760/