Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

[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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...