Avoiding memory leaking when implementing a binary search tree

So I have a binary search tree with something like this

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <iostream>
#include <string>
using namespace std;

struct Data
{
	string key;

	int* int_arr; //create a dynamically allocated array with this
	bool* bool_arr; //create a dynamically allocated array with this
};

struct Node
{
	Data* data; //pointer to data

	Node* pLeft;
	Node* pRight;
};

class BSTree
{
public:
	~BSTree()
	{
		empty(root);
	}

	void empty(Node* &cur)
	{
		if(cur)
		{
			empty(cur->pLeft);
			empty(cur->pRight);
			delete cur;
			cur = NULL; //<- is this necessary?
		}
	}
private:
	Node* root;
};


My question is, will the BSTree class' destructor deallocate the memory allocated for the data pointer and the dynamically allocated arrays as well? If not, how can I deallocate them to prevent memory leaking

Thank you for your time and patience
and the dynamically allocated arrays as well?
No

how can I deallocate them to prevent memory leaking
Add a destructor for Data where you delete its content.

If you'd have a destructor for Node you wouldn't need a function like empty(...). By the way data of Node isn't deleted either

EDIT: If you add a destructor you should add constructor as well to provide sane data
Last edited on
Thanks, you guys are the best
Topic archived. No new replies allowed.