Home > Backend Development > C++ > body text

Why Does `stringstream.str().c_str()` Cause a Memory Error in C ?

Mary-Kate Olsen
Release: 2024-11-15 05:01:02
Original
959 people have browsed it

Why Does `stringstream.str().c_str()` Cause a Memory Error in C  ?

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;
}
Copy after login

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();
Copy after login

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 (???)
Copy after login

All print statements now work correctly because:

  • cstr and cstr2どちらも有効な文字列ポインタです。
  • ss.str().c_str() is a temporary string that is bound to a const reference, extending its lifetime.

The above is the detailed content of Why Does `stringstream.str().c_str()` Cause a Memory Error in C ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template