在结构中分配字符串时的Seg错误 [英] Seg fault when assigning a string in a struct

查看:92
本文介绍了在结构中分配字符串时的Seg错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

struct Person {
    int age;
    string name;
};

int main() {
    struct Person* firstPerson;

    firstPerson = new Person();

    firstPerson->age = 23;
    firstPerson->name = "John Doe";

    cout << firstPerson->age << " " << firstPerson->name;
    return 0;
}

当我做上述一切都很好,没有seg故障。但是如果我把上面的改变为

When I do the above it all works well and there is no seg fault. However if I change the above to

int main() {
    struct Person* firstPerson;

    firstPerson = static_cast<struct Person*>(malloc(sizeof(struct Person)));
    firstPerson->age = 23;
    cout << firstPerson->age;
    firstPerson->name = "John Doe";

    return 0;
}

推荐答案

只能使用 malloc 创建POD结构。 malloc只分配内存,但是复杂的类也需要初始化。使用new分配包含更复杂(非POD)数据类型的结构(如 string )。如果你真的需要使用malloc,你可以使用placement new操作符:

You can only create POD structs using malloc alone. malloc only allocates memory, but complex classes need to be initialized as well. Use new to allocate structs containing more complex (non-POD) data types (as string). If you really need to use malloc you can use placement new operator:

void* foo = malloc(sizeof(struct Person));
firstPerson= new(foo) Person();

放置新操作符在已分配的内存块上执行给定类型的初始化(构造)。

Placement new operator executes initialization (construction) of given type on already allocated memory block.

这篇关于在结构中分配字符串时的Seg错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆