0

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();
}
Suraj Jain
  • 4,463
  • 28
  • 39
51k
  • 1,381
  • 3
  • 12
  • 22

3 Answers3

12

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.

James Kanze
  • 150,581
  • 18
  • 184
  • 329
5

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.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
0

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)

Community
  • 1
  • 1
Cyrille
  • 13,905
  • 2
  • 22
  • 41