Home >Backend Development >C++ >How to Correctly Allocate Memory for Structures Containing Strings in C ?

How to Correctly Allocate Memory for Structures Containing Strings in C ?

DDD
DDDOriginal
2024-12-01 09:47:12724browse

How to Correctly Allocate Memory for Structures Containing Strings in C  ?

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!

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