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

Why does deleting a ostringstream object as in my code leads to segmentation fault?

本文关键字:分段 错误 对象 ostringstream 我的 代码 删除 为什么      更新时间:2023-10-16
#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的内存空间

我错了吗?

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

只有你自己new delete的事情。 不要delete别人的东西。