Confusion over Conversions Between stringstream, string, and char*
This issue arises when converting the string obtained from stringstream.str().c_str() into a const char*. Understanding the memory management and lifetime of the returned string is crucial to avoid potential errors.
The code snippet demonstrates the issue:
#include <string> #include <sstream> #include <iostream> int main() { stringstream ss("this is a string\n"); string str(ss.str()); const char* cstr1 = str.c_str(); const char* cstr2 = ss.str().c_str(); cout << cstr1 // Prints correctly << cstr2; // ERROR, prints out garbage system("PAUSE"); return 0; }
The assumption that stringstream.str().c_str() can be assigned to a const char* is incorrect. This leads to a bug where cstr2 prints out garbage.
Understanding the Memory Management
stringstream.str() returns a temporary string object that is valid only until the end of the current expression. When the expression completes, the temporary object is destroyed, and the pointer to its data (returned by c_str()) becomes invalid.
Resolving the Error
To resolve this issue, the temporary string object must be stored in a separate variable, such as:
const std::string tmp = stringstream.str(); const char* cstr2 = tmp.c_str();
By storing the temporary object in tmp, the lifetime of the pointer is extended, and printing cstr2 now works correctly.
Bonus Points Explanation
In the modified code block:
cout << cstr // Prints correctly << ss.str().c_str() // Prints correctly << cstr2; // Prints correctly (???)
All print statements now work correctly because:
以上是為什麼 `stringstream.str().c_str()` 會導致 C 記憶體錯誤?的詳細內容。更多資訊請關注PHP中文網其他相關文章!