我在使用字符串流时遇到问题
当我运行这段代码时,第一个 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;
}
任何想法将不胜感激
最佳答案
你有两个问题:
string CJpsURI::getURIwithSipIpPort()
{
stringstream ss;
ss << "sip:" << m_ipAddr << ":" << m_portAddr;
return ss.str();
}
A
char*
指向char
的数组秒。这里你想要在getURIwithSipIpPort
返回的字符串中找到的数组. 但是一旦这一行结束,那段内存就会被释放!没有任何东西卡在上面。所以你真正需要做的是:字符串 s{localIp.getURIwithSipIpPort()};
关于c++ - 字符串流数据损坏的问题。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26981433/