Boa noite pessoal, venho enfrentando um problema referente a funcao free() no método destroy(), para desalocação de memória.
Apos inserir valores na arvore binaria em um primeiro momento eu até consigo desalocar através da funcao free(), porem se apos essa desalocação eu tentar imprimir a arvore ou tentar desalocar a memória novamente (Para testar se o sistema barra uma tentativa de imprimir uma arvore vazia ou uma nova desalocação de memória ), o sistema lança uma exceção e aborta.
Ja tentei várias coisas, mas como tenho pouco conhecimento sobre ponteiros nao obtive exito.
Agradeço desde já
#pragma once
class NodeTree {
public:
int value;
NodeTree * left;
NodeTree * right;
NodeTree() {
value = 0;
}
};
#pragma once
#include "NodeTree.h"
#include <iostream>
using namespace std;
class BinaryTree {
public:
NodeTree * root;
BinaryTree() {
root = NULL;
}
bool isEmpty(NodeTree * obj) {
return obj == NULL;
}
void clean(int opcao) {
if (isEmpty(root)) {
cout << "A arvore ja esta vazia, nao e possivel esvazia-la novamente\n";
return;
}
if (opcao == 1) {
makeEmpty();
}
else {
destroy(root);
cout << "A arvore foi esvaziada e a memoria desalocada\n";
}
}
void makeEmpty() {
root = NULL;
cout << "A arvore foi esvaziada\n";
return;
}
void destroy(NodeTree * obj) {
if (!isEmpty(obj)) {
destroy(obj->left);
destroy(obj->right);
free(obj);
}
obj = NULL;
}
void insert(int num) {
NodeTree * node = new NodeTree;
node->value = num;
insertNeatly(node, root);
}
void insertNeatly(NodeTree * node1, NodeTree *&root1) {
if (root1 == NULL) {
node1->left = NULL;
node1->right = NULL;
root1 = node1;
}
else {
if (node1->value > root1->value) {
insertInOrder(node1, root1->right);
}
else if (node1->value < root1->value) {
insertInOrder(node1, root1->left);
}
else {
return;
}
}
}
void print(NodeTree * obj) {
if (obj == NULL)
return;
printInOrder(obj->left);
cout << obj->value << " ";
printInOrder(obj->right);
}
};
#include "stdafx.h"
#include "BinaryTree.h"
#include <iostream>
#include <stdlib.h>
using namespace std;
int main(){
BinaryTree tree;
int sentinela = 0;
int numero;
int opcao;
while (sentinela != 4) {
system("cls");
cout << "Opcoes:\n\n1-Inserir ordenadamente\n2-Exibir em ordem\n3-Esvaziar arvore\n4-Sair\n\nOpcao desejada: ";
cin >> sentinela;
if (sentinela == 1) {
system("cls");
cout << "Digite um numero: ";
cin >> numero;
tree.insert(numero);
}
if (sentinela == 2) {
system("cls");
cout << "Exibicao em ordem: ";
tree.print(tree.root);
system("PAUSE");
}
if (sentinela == 3) {
system("cls");
cout << "Escolha a opcao: 1-Esvaziar / 2- Esvaziar e desalocar memoria: ";
cin >> opcao;
tree.clean(opcao);
system("PAUSE");
}
}
return 0;
}