Где утечка памяти и есть ли она вообще?
Изучаю структуры данных. Сделал бинарное дерево. Однако библиотека для детектирования утечек памяти говорит, что у меня происходит утечка памяти в методе add_node(), где я динамически выделяю память для узла. Но я же вроде удаляю и освобождаю память в деструкторе и в методе delete_tree()/delete_subtree()? Тогда почему утечка памяти? Или это утилита глючит?
Заранее спасибо за помощь, советы и критика приветствуются.
Вот код:
#include <iostream>
#include <stack>
#define __CRTDBG_MAP_ALLOC
#include <crtdbg.h>
#define DEBUG_NEW new(_NORMAL_BLOCK, __FILE__, __LINE__)
#define new DEBUG_NEW
using namespace std;
class Tree {
private:
struct TNode {
int memory;
TNode* left;
TNode* right;
};
TNode* root;
bool empty;
public:
using Node = TNode;
Tree() {
this->root = new Node;
this->root->memory = NULL;
this->root->left = NULL;
this->root->right = NULL;
this->empty = true;
}
~Tree() {
if (not this->empty) {
delete_tree();
}
}
bool* is_empty() {
return &this->empty;
}
Node* get_root() {
return this->root;
}
void delete_subtree(Node* sub_root) {
stack <Node*> nodes_to_delete;
do {
if (sub_root == NULL) {
break;
}
if (sub_root->right != NULL) {
nodes_to_delete.push(sub_root->right);
}
if (sub_root->left != NULL) {
nodes_to_delete.push(sub_root->left);
}
delete sub_root;
sub_root = NULL;
if (not nodes_to_delete.empty()) {
sub_root = nodes_to_delete.top();
nodes_to_delete.pop();
}
} while (not nodes_to_delete.empty());
}
void delete_tree() {
delete_subtree(this->root);
this->root = NULL;
this->empty = true;
}
void add_node(int value) {
Node* rRoot = this->root;
Node* node = new Node;
node->memory = value;
node->left = NULL;
node->right = NULL;
while (true) {
if (*is_empty() == true) {
rRoot->memory = value;
this->empty = false;
break;
}
else if (value < rRoot->memory) {
if (rRoot->left == NULL) {
rRoot->left = node;
break;
}
else {
rRoot = rRoot->left;
}
}
else if (value > rRoot->memory) {
if (rRoot->right == NULL) {
rRoot->right = node;
break;
}
else {
rRoot = rRoot->right;
}
}
else {
break;
}
}
}
void print_tree_vertical() {
stack <Node*> nodes_stack;
Node* sub_root = get_root();
while (true) {
if (sub_root == NULL or not sub_root) {
cout << "Нет корня!!!\n";
break;
}
if (sub_root->memory == NULL) {
cout << "Value: " << sub_root->memory << "\n";
}
else {
cout << "Value: " << sub_root->memory << "\n";
if (sub_root->left != NULL) {
cout << "Left: " << sub_root->left->memory << "\n";
}
if (sub_root->right != NULL) {
cout << "Right: " << sub_root->right->memory << "\n";
}
cout << "\n";
}
if (sub_root->right != NULL) {
nodes_stack.push(sub_root->right);
}
if (sub_root->left != NULL) {
nodes_stack.push(sub_root->left);
}
if (not nodes_stack.empty()) {
sub_root = nodes_stack.top();
nodes_stack.pop();
}
else {
break;
}
}
}
};
int main() {
setlocale(LC_ALL, "RUSSIAN");
int arr[15] = {5, 2, 3, 4, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
Tree tree = Tree();
/*tree.add_node(5);
tree.add_node(4);
tree.add_node(6);
tree.add_node(1);
tree.delete_tree();*/
for (int i = 0; i < 15; i++) {
tree.add_node(arr[i]);
}
tree.print_tree_vertical();
cout << "-----------------------\n";
tree.delete_tree();
tree.print_tree_vertical();
system("pause"); _CrtDumpMemoryLeaks(); return 0;
}
В соответствии с комментариями изменил метод таким образом, чтобы память выделялась только тогда, когда ее нужны выделить, однако, утилита все равно ругается на 115 строчку, где память выделяется. Причем именно на ту часть, где выделение идет в случае value > rRoot->memory. Хотя присвоение идет. Где-то еще закопалась ошибка? Вот новый код метода:
void add_node(int value) {
Node* rRoot = this->root;
while (true) {
if (*is_empty() == true) {
rRoot->memory = value;
this->empty = false;
break;
}
else if (value < rRoot->memory) {
if (rRoot->left == NULL) {
Node* node = new Node;
node->memory = value;
node->left = NULL;
node->right = NULL;
rRoot->left = node;
break;
}
else {
rRoot = rRoot->left;
}
}
else if (value > rRoot->memory) {
if (rRoot->right == NULL) {
Node* node = new Node;
node->memory = value;
node->left = NULL;
node->right = NULL;
rRoot->right = node;
break;
}
else {
rRoot = rRoot->right;
}
}
else {
break;
}
}
}