I have an issue using stringstreams
When I run this code the first printf is fine but at some point it gets contaminated and prints out a shorter string.
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 } It almost appears that the *s is pointing to the out string on the stack which gets destroyed. But that should not be happening since I am returning out and not a reference to out.
But this seems to work.
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; } Any ideas would be appreciated
out,sis the result of callingc_str()on a temporarystring, so dereferencing it is undefined. In both cases. It's just bad luck that it "works".