在C ++中出现奇怪的行为,cout语句是否需要防止应用程序崩溃?

时间:2014-12-30 16:14:22

标签: c++ cout

我正在尝试解决算法问题,但目击了奇怪的行为。每当我注释掉第一个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

1 个答案:

答案 0 :(得分:5)

问题是你永远不会在buffer中为string_to_ints分配内存。由于这是未定义的行为任何可能发生,包括在cout到位时似乎工作而在cout被移除时不工作。

最简单的解决方案是使用std::string代替char*作为缓冲区。然后你就不用做自己的内存管理了。