Coverity与Purify报内存问题,求stringstream正确使用方法
Hey there! Let's break down why Coverity and Purify are flagging memory problems in your code—this is a super common gotcha with std::string and c_str() that trips up a lot of folks.
The Root Cause
Let's zoom in on this problematic line:
const char * filename=ss.str().c_str();
When you call ss.str(), it returns a temporary std::string object. This temporary only exists for the duration of that single line of code. Once the line finishes executing, the temporary string gets destroyed, and the memory it was managing is freed up.
Here's the critical mistake: c_str() returns a pointer directly to the internal character array of that temporary string. When the temporary is destroyed, this pointer becomes a dangling pointer—it points to memory that's no longer valid. When you later run std::cout << filename, you're accessing invalid memory, which is exactly what those static analysis tools are warning you about.
Fixes to Resolve the Issue
You have two straightforward ways to fix this:
Store the string in a persistent variable
Keep thestd::stringalive for as long as you need to use the pointer:int main() { int count=123; std::stringstream ss; ss<< "123_"<< count << "_" << ".log"; std::string filename_str = ss.str(); // Hold onto the string const char * filename = filename_str.c_str(); std::cout << filename << std::endl; return 0; }Now
filename_stris a local variable that stays alive until the end ofmain(), so the pointer fromc_str()remains valid the whole time you use it.Skip the raw pointer entirely
If your only goal is to output the string, you can use thestd::stringdirectly without ever dealing with aconst char*:int main() { int count=123; std::stringstream ss; ss<< "123_"<< count << "_" << ".log"; std::cout << ss.str() << std::endl; return 0; }This is even cleaner and eliminates the risk of dangling pointers altogether.
Key Takeaway
Always remember: the pointer returned by c_str() is only valid as long as the original std::string object exists and isn't modified (like being reassigned or resized). If the string is destroyed or changed, that pointer becomes invalid immediately.
内容的提问来源于stack exchange,提问作者Eric Lin

