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

為什麼在 C 字串初始化中使用 malloc() 會導致分段錯誤?

Barbara Streisand
發布: 2024-11-15 05:38:02
原創
774 人瀏覽過

Why Does Using malloc() with C++ string Initialization Lead to Segmentation Faults?

How to Handle C++ String Initialization When Memory Allocated with malloc()?

In C++, attempting to use the malloc() function to create a structure containing a std::string may result in segmentation faults. To understand this issue, consider the following example:

struct example {
  std::string data;
};

int main() {
  example *ex = (example *)malloc(sizeof(*ex)); // Allocating memory for the structure
  ex->data = "hello world";                   // Assigning a value to the std::string member
  std::cout << ex->data << std::endl;       // Printing the value of the std::string member
}
登入後複製

When executing this code, a segmentation fault occurs. This happens because simple memory allocation using malloc() does not properly initialize the std::string object within the structure.

Solution: Using new Operator

To resolve this problem, avoid using malloc() when working with classes or structures containing non-trivial constructors, such as std::string. Instead, utilize the new operator to allocate memory and construct the object correctly:

example *ex = new example; // Allocating memory and constructing the object
ex->data = "hello world";
std::cout << ex->data << std::endl;
登入後複製

Advanced Technique: Placement New with malloc()

Alternatively, if you insist on using malloc(), you can employ a technique called "placement new":

void *ex_raw = malloc(sizeof(example)); // Raw memory allocation
example *ex = new(ex_raw) example;      // Placement new to construct the object
登入後複製

However, it is highly recommended to use the new operator for simplicity and safety.

以上是為什麼在 C 字串初始化中使用 malloc() 會導致分段錯誤?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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