Sebastián Mestre
Sebastián Mestre

Reputation: 223

Allocate memory for a vector of pointers inside of a structure

I have the following structure:

struct node{
  char name;
  vector<node*> children;

  void addChild(char name){
    node *newChild = (node*)malloc(sizeof(node));
    newChild->name = name;
    children.push_back(newChild);
  }
};

The code above compiles but crashes with a std::bad_alloc prompt whenever addChild is called for any node that was created using addChild.

It seems to me like i should somehow be allocating memory for the vector as well, but i am unsure about how i would go about doing that.

I am a "begginer" and know very little about memory allocation so any help would be appreciated.

Thanks in advance.

Upvotes: 1

Views: 527

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409166

Don't use malloc and free in C++. Especially for objects that needs to have their constructor called, since malloc does not call the constructor.

In your case it means that the std::vector constructor will not be called, and you will have undefined behavior when you use the vector.

Use new and delete instead.

Any good beginners book should have told you this.

Upvotes: 6

Related Questions