首页 >后端开发 >C++ >如何在 C 中为包含 std::strings 的结构正确分配内存?

如何在 C 中为包含 std::strings 的结构正确分配内存?

Barbara Streisand
Barbara Streisand原创
2024-11-24 06:17:14780浏览

How Can I Correctly Allocate Memory for Structures Containing std::strings in C  ?

在 C 中使用 std::String 处理结构:导航内存分配

在 C 中,处理包含 std::string 和 的结构时使用 malloc() 可能会出现某些陷阱。考虑以下示例:

struct example {
 std::string data;
};

int main() {
 example *ex = (example *)malloc(sizeof(*ex));
 ex->data = "hello world";
 std::cout << ex->data << std::endl;
}

执行时,该程序因分段错误而崩溃。这种行为源于 malloc() 的固有性质和 std::strings 的构造。

Maldvertising 和内存分配

与 new 不同,malloc() 只是分配原始内存。在这种情况下,尝试使用 malloc()-ed 内存作为“真实”对象可能会导致未定义的结果。要正确实例化内存中的对象,请使用 new 而不是 malloc():

example *ex = new example;

欺骗 malloc() 进行合作

或者,通过使用 malloc 的组合() 和放置 new 运算符,在 malloc()-ed 中构造对象是可行的内存:

void *ex_raw = malloc(sizeof(example));
example *ex = new(ex_raw) example;

但是,在使用 std::strings 管理结构的上下文中,采用这些技术可能是不必要的。

以上是如何在 C 中为包含 std::strings 的结构正确分配内存?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn