-3

I have the folowing structure defined

typedef struct NodeMulti{
    int key;
    vector<NodeMulti*> child;
};

in a function let's say I have:

NodeMulti* newNode = (NodeMulti*)malloc(sizeof(NodeMulti));
NodeMulti* anotherNode = (NodeMulti*)malloc(sizeof(NodeMulti));
newNode->child.push_back(anotherNode);

it does not work, any suggestions on how to fix it? if i try changing the key value, it works; for ex: 'newNode->key =...` works fine thanks!

wimh
  • 15,072
  • 6
  • 47
  • 98

1 Answers1

1

In C++ use new, not malloc.

malloc only allocates memory but will not call constructors. E.g. your vector is left uninitialized, thus trying to access it (e.g. push_back) invokes undefined behavior.

new both allocates memory and calls constructors, so your vector will be initialized using its default constructor, which creates an empty vector.

Also, in C++ you can declare a struct just like so:

struct NodeMulti { ... };

I.e. no need for the typedef. Also in your code you're not even assigning a name in the typedef declaration, so it has no effect.

Community
  • 1
  • 1
Emil Laine
  • 41,598
  • 9
  • 101
  • 157