Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
195 views
in Technique[技术] by (71.8m points)

Accessing member of a C++ object allocated with malloc?

[Editor's note: I have edited the title to try to make this useful to others in the future. To give the answerers credit, this was just a "why does this not work?" question when they answered it!]

The following code crashes at the top -> ... line with a segmentation fault, regardless of what Node* is trying to be pushed onto the vector children. Does anyone know what might be causing this?

struct Node
{
    string data;
    struct Node* parent;
    vector<struct Node*> children;
};

struct Node* push(string word, struct Node* top)
{
    Node* temp = (struct Node*) malloc(sizeof(struct Node));
    temp -> data = word;
    temp -> parent = top;
    return temp;
}

int main()
{
    Node* top = push("blah", NULL);
    Node* temp = NULL;
    top -> children.push_back(temp);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem is that malloc will not call constructors. And you're counting on the vector children to be constructed.

Replace:

Node* temp = (struct Node*) malloc(sizeof(struct Node));

With:

Node* temp = new Node;

malloc (from C) and new (from C++) will both allocate the memory you need, but only new will call the required constructors, as C doesn't use them. If you're not positive that you need malloc, use new.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...