I am relatively new to c++ programming, especially when dealing with OOP and pointers.
I am trying to implement a binary search tree, and here is the code I have
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode() : val(0), left(NULL), right(NULL){};
TreeNode(int v) : val(v), left(NULL), right(NULL){};
TreeNode(int v, TreeNode* l, TreeNode* r) : val(v), left(l), right(r){};
};
void insert(TreeNode* root, TreeNode* v) {
// inserts v into root, assuming values distinct
if (root == NULL) {
root = v; // L52
return;
}
if (v == NULL) {
return;
}
// traverse through tree using structure of BST
TreeNode* cur = root;
while (cur != NULL) {
if (cur->val <= v->val) {
if (cur->right == NULL) {
cur->right = new TreeNode(v->val);
break;
}
cur = cur->right;
} else if (cur->val >= v->val) {
if (cur->left == NULL) {
cur->left = new TreeNode(v->val);
break;
}
cur = cur->left;
}
}
}
void insert(TreeNode* root, int v) {
insert(root, new TreeNode(v)); // L78
}
Now, I have two questions.
I realised that the L52 labelled above would not work. For example, if I do
TreeNode* node = new TreeNode(5); TreeNode* empty = NULL; insert(empty, node);
, it would not work. I am not sure how to fix this, so any help would be great.Running clang-tidy on my code, I get the following slightly confusing warning:
./main.cpp:78:69: warning: Potential memory leak [clang-analyzer-cplusplus.NewDeleteLeaks]
void insert(TreeNode* root, int v) { insert(root, new TreeNode(v)); }
^
./main.cpp:132:3: note: Calling 'insert'
insert(node, 3);
^
./main.cpp:78:51: note: Memory is allocated
void insert(TreeNode* root, int v) { insert(root, new TreeNode(v)); }
^
./main.cpp:78:69: note: Potential memory leak
void insert(TreeNode* root, int v) { insert(root, new TreeNode(v)); }
^
I am not sure what this means, and whether it would be dangerous in any way. I found this from the LLVM docs and it seems that the temporary new TreeNode(v)
is causing the problem. What is a better way to achieve what I want? Any further explanation or resources that I can read would be great.
Of course, any improvement to my bad coding style would be great as well ;) formatter saves the day.
Thank you!