51k
51k

Reputation: 1443

Segmentation fault

Tried to trace, but did not find a reason why the following code is giving "Access violation" in VC++, and segmentation fault in gcc..

#include <vector>
#include <iostream>
using namespace std;

typedef struct node
{
    std::string data;
    vector <struct node*> child;
}NODE, *PNODE;

int main()
{
    PNODE head;
    head = (PNODE) malloc(sizeof(NODE));

    head->data.assign("hi");

    printf("data %s", head->data.c_str());
    getchar();
}

Upvotes: 0

Views: 310

Answers (3)

Cyrille
Cyrille

Reputation: 14553

I agree with previous answers.

I should add that it's best practice to avoid using namespace (see here)

And in C++, avoid using C-like struct declaration :

typedef struct node
   {
       std::string data;
       vector  child;
   }NODE, *PNODE;

should be:

struct Node
{
    std::string data;
    std::vector<Node> child;
}

then:

Node head;

or:

Node* head = new Node;

If you are using c++, use std::cout instead of printf

There are c++ cast operator too : dynamic_cast, static_cast, const_cast, reinterpret_cast (see here)

Upvotes: 0

NPE
NPE

Reputation: 500773

Use new rather than malloc to create C++ objects on the heap.

The following:

head = (PNODE) malloc(sizeof(NODE));

should read

head = new NODE;

The reason malloc() doesn't work here is that it doesn't call object constructors.

Upvotes: 5

James Kanze
James Kanze

Reputation: 154007

And why on earth do you think it should work? You use malloc, rather than new, so no constructors are called, and everything you do accesses uninitialized memory.

Upvotes: 12

Related Questions