Home >Backend Development >C++ >Why Does Assigning `stringstream.str().c_str()` to a `const char*` Lead to Garbage Output?

Why Does Assigning `stringstream.str().c_str()` to a `const char*` Lead to Garbage Output?

Barbara Streisand
Barbara StreisandOriginal
2024-11-16 17:16:03518browse

Why Does Assigning `stringstream.str().c_str()` to a `const char*` Lead to Garbage Output?

stringstream, string, and char* Conversion Confusion

This article addresses the issue of assigning a const char* to the string returned by stringstream.str().c_str().

Problem Explanation

stringstream.str() constructs a temporary string object that is destroyed at the end of the expression. When assigning this temporary string to a const char*, the pointer references the deleted string, resulting in garbage output.

Here's an example:

stringstream ss("this is a string\n");
const char* cstr = ss.str().c_str();

In the above code, after the expression ends, the temporary string created by stringstream.str() is deleted, causing cstr to point to an invalid memory location.

Solution

To rectify this issue, the temporary string should be copied to another string object before converting it to a const char*. This can be achieved using the following approach:

string tmp = stringstream.str();
const char* cstr = tmp.c_str();

Bonus Points Explanation

The following modified code prints the strings correctly:

cout << cstr << ss.str().c_str() << cstr2;

This modification works because:

  • cstr points to a const char* that was created from a string object with a known lifetime.
  • ss.str().c_str() returns a const char* that points to the temporary string, which is now protected by the const reference returned by stringstream.str()
  • cstr2 points to the same temporary string as ss.str().c_str(), but it is not const, so it can be assigned to a temporary char* that is destroyed at the end of the cout statement.

The above is the detailed content of Why Does Assigning `stringstream.str().c_str()` to a `const char*` Lead to Garbage Output?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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