首頁 > 後端開發 > C++ > 主體

為什麼 `stringstream.str().c_str()` 會導致 C 記憶體錯誤?

Mary-Kate Olsen
發布: 2024-11-15 05:01:02
原創
958 人瀏覽過

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;
}
登入後複製

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:

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

以上是為什麼 `stringstream.str().c_str()` 會導致 C 記憶體錯誤?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板