c++ - 字符串流数据损坏的问题。

标签 c++ string stringstream

我在使用字符串流时遇到问题

当我运行这段代码时,第一个 printf 没有问题,但在某些时候它被污染并打印出一个较短的字符串。

string CJpsURI::getURIwithSipIpPort()
{
    stringstream ss;
    ss << "sip:" << m_ipAddr << ":" << m_portAddr;
    string out = ss.str();
}

main() {

    CJpsURI localIp();
    localIp.setIpPort("192.168.88.1", 5060);

    char *s = localIp.getURIwithSipIpPort().c_str();

    printf("This is the sip port: %s", s);  // this may be ok  -- sip:192.168.88.1:5060
    // do some stuff
    printf("This is the sip port: %s", s);  // wrong; -- sip:192.168.8/030/004

}

看起来 *s 几乎指向堆栈上被销毁的输出字符串。但这不应该发生,因为我要返回而不是对 out 的引用。

但这似乎有效。

string CJpsURI::getURIwithSipIpPort()
{
    string out = (boost::format("sip:%1%:%2%") % m_ipAddr % m_portAddr).str();
    return out;
}

main() {

    CJpsURI localIp();
    localIp.setIpPort("192.168.1.1", 5060);

    char *s = localIp.getURIwithSipIpPort().c_str();

    printf("This is the sip port: %s", s);  // this may be ok
    // do some stuff
    printf("This is the sip port: %s", s);  // this will be ok too;

}

任何想法将不胜感激

最佳答案

你有两个问题:

  1. 作为remyabelGalik指出:你的函数没有返回。所以我同意 Galik您需要调整您的功能以:

string CJpsURI::getURIwithSipIpPort()
{
stringstream ss;
ss << "sip:" << m_ipAddr << ":" << m_portAddr;
return ss.str();
}

  1. A char*指向 char 的数组秒。这里你想要在 getURIwithSipIpPort 返回的字符串中找到的数组. 但是一旦这一行结束,那段内存就会被释放!没有任何东西卡在上面。所以你真正需要做的是:

    字符串 s{localIp.getURIwithSipIpPort()};

关于c++ - 字符串流数据损坏的问题。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26981433/

相关文章:

c++ - 如果程序从 linux 中的两个终端运行,fork 的共享内存是否共享

java - 删除包含表达式的单词?

c++ - 为什么 strtok 不能与 stringstream 一起使用?

c++ - 在cout中禁用逗号?

c++ - 在 OpenCV 中合并重叠矩形

c++ - std::map:当元素不可默认构造时创建/替换元素

Java Tic Tac Toe 错误

检查两个字符串是否是 C 中的排列

c++ - 字符串流错误 : cannot access private member declared in class 'std::basic_ios<_Elem,_Traits>'

c++ -//! [0] 在 Qt 源代码中