Some C++ programmers say that dynamic memory allocation is bad and should be avoided whenever possible. I tried making a binary tree data structure without using dynamic memory allocation, and it doesn't work. Here's what I tried:
struct BTNode {
BTNode *left = 0, *right = 0;
int data;
BTNode(int d_) { data = d_; }
void insert(int d_) {
BTNode n(d_);
if (d_ <= data)
if (left == 0) left = &n;
else left->insert(d_);
else
if (right == 0) right = &n;
else right->insert(d_);
}
}
And then doing this in main...
BTNode root(8);
root.insert(9);
root.insert(10);
cout << root.right->right->data;
results in a segfault, because the BTNode containing the data went out of scope a long time ago.
My question is, how is one supposed to structure a pointer-based binary tree like this without the use of new and delete?
BTNodewith sufficient elements and use it as memory pool, taking nodes from the array.std::vector<BTNode>to hold all the nodes. I personally don't think that is necessary. I would simply doauto newNode = new BTNode(8);and then set the appropriate pointers.newanddeleteyourself. There's actually nothing wrong with dynamic memory management