Allocating Structures Containing Strings with Malloc
When attempting to manage memory for a structure containing std::string members using malloc(), segfaults may occur. This is because malloc() provides raw memory allocation rather than constructing objects.
Using new for Object Allocation
To correctly allocate memory for a struct with std::string members, use new instead of malloc(). new will automatically construct the object in the allocated memory.
Example:
#include <iostream> #include <string> struct example { std::string data; }; int main() { example *ex = new example; // Allocate memory using 'new' ex->data = "hello world"; std::cout << ex->data << std::endl; delete ex; // Release allocated memory when done }
Placement new for Raw Memory Management
If memory has already been allocated using malloc(), it's possible to use placement new to construct the object in that memory.
Example:
void *ex_raw = malloc(sizeof(example)); example *ex = new(ex_raw) example; // Construct the object in allocated memory using placement 'new'
However, using new directly is generally preferred over placement new for object construction.
The above is the detailed content of How to Correctly Allocate Memory for Structures Containing Strings in C ?. For more information, please follow other related articles on the PHP Chinese website!