为什么在我的代码中删除ostringstream对象会导致分段错误?

时间:2012-05-11 18:36:27

标签: c++ stringstream ostringstream

#include <iostream>
#include <sstream>
#include <fstream>
#include <iomanip>
#include <string>

using namespace std;

int main()
{
    ostringstream out;
    ostringstream tmpstr;
    tmpstr << "ritesh is here";
    out << tmpstr.str().c_str();
    out << endl;
    cout << out.str();
    if(tmpstr.rdbuf()!=NULL)
        cout << "tmpstr not null" <<endl;
    else
        cout << "tmpstr null" <<endl;
    delete tmpstr.rdbuf();   // This line gives me segmentation fault
    cout <<"deleted" << endl;
}

delete tmpstr.rdbuf();给出了细分错误。我猜rdbuf返回char *指针因此。我可以使用删除来释放分配给tmpstr

的内存空间

我错了吗?

1 个答案:

答案 0 :(得分:7)

是的,你认为你可以delete你没有分配的东西是错误的。

您自己只有delete件事new。不要delete别人的东西。