我可以将返回值ostringstream.str()发送到另一个ostringstream吗

时间:2020-02-11 11:37:47

标签: c++ gdb

我可以从函数返回oss.str()并将该返回值发送到另一个ostringstream吗?

像这样

std::string funcOne() 
{
    std::ostringstream oss;
    oss << "time";
    return oss.str();
}

//...
//in another function,

std::string funcTwo() {
    std::ostringstream oss;
    oss << funcOne();
    return oss.str();
}

//...
DEBUG("%s", funcTwo().c_str());

编辑:我为什么要问这个?

我在funcOne()的oss.str()崩溃了

#0  0x00007fd7a5a53f67 in raise () from /lib64/libc.so.6
#1  0x00007fd7a5a5533a in abort () from /lib64/libc.so.6
#2  0x00007fd7a63b1919 in std::string::_Rep::_S_create(unsigned long, unsigned long, std::allocator<char> const&) () from /usr/lib64/libstdc++.so.6
#3  0x0000000000000005 in ?? ()
#4  0x00007fd7717f8730 in ?? ()
#5  0x00007fd7717f872f in ?? ()
#6  0x00007fd7a6656660 in vtable for std::ios_base::failure () from /usr/lib64/libstdc++.so.6
#7  0x00007fd7a5a92e7e in __libc_message () from /lib64/libc.so.6
#8  0x00007fd7a5a98646 in malloc_printerr () from /lib64/libc.so.6
#9  0x00007fd7a5a9ab45 in _int_malloc () from /lib64/libc.so.6
#10 0x00007fd7a5a9c3d0 in malloc () from /lib64/libc.so.6
#11 0x00007fd7a6373598 in operator new(unsigned long) () from /usr/lib64/libstdc++.so.6
#12 0x00007fd7a63b1919 in std::string::_Rep::_S_create(unsigned long, unsigned long, std::allocator<char> const&) () from /usr/lib64/libstdc++.so.6
#13 0x00007fd7a63b1c92 in std::string::_M_mutate(unsigned long, unsigned long, unsigned long) () from /usr/lib64/libstdc++.so.6
#14 0x00007fd7a63b22ee in std::string::_M_replace_safe(unsigned long, unsigned long, char const*, unsigned long) () from /usr/lib64/libstdc++.so.6
#15 0x00007fd7a63b33bf in std::string::replace(unsigned long, unsigned long, char const*, unsigned long) () from /usr/lib64/libstdc++.so.6
#16 0x00007fd7a63ac328 in std::basic_ostringstream<char, std::char_traits<char>, std::allocator<char> >::str() const ()
   from /usr/lib64/libstdc++.so.6

我也看到一些情况,oss.str()返回一个临时对象,无法对其进行进一步的操作,因为在str()调用后它将被销毁。

1 个答案:

答案 0 :(得分:0)

您在malloc实现中崩溃。

在此类崩溃的99.9999%的实例中,问题是堆损坏,并且通常与崩溃的代码完全无关。

堆损坏的示例:删除未分配的内存,两次删除一些内存,堆分配的缓冲区溢出等。

使用Address SanitizerValgrind快速找到堆损坏的根源。