访问结构内的列表时出现分段错误 [英] Segmentation fault when accessing a list inside a struct

查看:61
本文介绍了访问结构内的列表时出现分段错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我会尽力弄清楚.

这是我的结构:

struct scopeList{
       int id;
       list<int> internal_list;
};
typedef struct scopeList scopeList_T;

这是给我细分的代码.

int main(){
    scopeList_T* t1 = (scopeList_T*) malloc(sizeof(scopeList_T));
    t1->id = 5; //works fine
    t1->internal_list.push_front(5); //segmentation fault
} 

由于我正在分配内存并且访问id很好,为什么这会给我分段错误?我必须先对列表做些特别的事情吗?

Since I am allocating memory and accessing id is fine, why is does this give me a segmentation fault? Do I have to do something special to the list first?

谢谢!

推荐答案

使用new代替malloc

sopeList_T* t1 = new scopeList_T;

malloc不运行任何构造函数.当需要释放该struct时,请使用delete而不是free-您不能freenew分配的对象(并且free不会调用析构函数).

malloc doesn't run any constructors. When you need to release that struct, use delete rather than free - you can't free objects allocated with new (and free doesn't call destructors).

您也不需要typedef,struct声明就足够了.

You don't need that typedef either, the struct declaration is enough.

struct scopeList {
    int id;
    list<int> internal_list;
};

int main()
{
    scopeList *t = new scopeList;
    ....
    delete t;
    ....
}

这篇关于访问结构内的列表时出现分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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