Segmentation fault in function insereAVN

Segmentation error in function insereAVN with keys above 7940. Help!

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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289

#include <cstdlib>
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <time.h>
#include <sstream>
#include <string>
#include <cstring>
#include <string.h>

using namespace std;

typedef int tipoChave;

struct dados {
    tipoChave chave;
    long int dado1;
    char dado2[1000];
};

struct Elemento {
    dados info;
    Elemento *anterior, *proximo;
};

typedef struct {
    Elemento *primeiro, *ultimo;
} ListaEncadeada;

typedef struct TipoNo *aponta;

typedef struct TipoNo {
    dados registro;
    int alturaEsq, alturaDir, FB;
    aponta esq, dir;
} TipoNo;

//  Funções
void iniciarArvore(aponta *s);
void insereAVN(dados dado, aponta *p);
void lerarquivo(ListaEncadeada *lista, string nome);
bool verificar(ListaEncadeada lista, tipoChave chave);
void gerarchaves(ListaEncadeada *lista, int quant, int op);
void menu();
int main();

void iniciarArvore(aponta *s) {
    (*s) = NULL;
}

void insereAVN(dados dado, aponta *p) {
    if (*p == NULL) {
        (*p) = (aponta) malloc(sizeof (TipoNo));
        (*p)->dir = (*p)->esq = NULL;
        (*p)->registro = dado;
	cout << (*p)->registro.chave << endl;
        return;
    } else {
		if (dado.chave < (*p)->registro.chave) {
			insereAVN(dado, &(*p)->esq);
            return;
		}
		if (dado.chave > (*p)->registro.chave) {
			insereAVN(dado, &(*p)->dir);
            return ;
		} else {
			cout << "\nError: O registro já existe!\n";
		}
	}
}

void lerarquivo(ListaEncadeada *lista, string nome) {
    ifstream arquivo;

    nome = nome + ".txt";

    if (nome.substr(nome.length() - 8, nome.length()) == (".txt.txt")) {
        nome = nome.substr(0, nome.length() - 4);
        cout << nome;
    }

    arquivo.open(nome.c_str());

    if (arquivo.fail()) {
        cout << "\nArquivo não encontrado!\n";
        menu();
    }

    dados dado;

    while (!arquivo.eof()) {
        arquivo >> dado.chave >> dado.dado1 >> dado.dado2;
        if (lista->ultimo != NULL) {
            if (dado.chave == lista->ultimo->info.chave) {
                goto fim;
            }
        }
lista como parametros
        inserirElemento(lista, dado);
    }

fim:
    cout << "\nLeitura completa do arquivo " << nome << "!\n";

    arquivo.close();
}

bool verificar(ListaEncadeada *lista, tipoChave chave) {
    Elemento *elementoP = new Elemento;
	Elemento *elementoU = new Elemento;
	
	elementoP = lista->primeiro; 
	elementoU = lista->ultimo;
	
    while (elementoP != elementoU) {
        if ((elementoP)->info.chave == chave || (elementoU)->info.chave == chave) {
            return true;
        }
        elementoP = elementoP->proximo;
        elementoU = elementoU->anterior;
    } 
    if (elementoP != NULL && elementoP->info.chave == chave) {
        return true;
    }

    return false;
}

void gerarchaves(ListaEncadeada *lista, int quant, int op) {
    tipoChave chave;
    long int dado1;
    int TAM;
    dados dado;

    srand(time(NULL));

    for (int i = 0; i < quant; i++) {
        TAM = 1 + (rand() % 10);
        char *dado2 = new char[TAM];

        if (op == 1) {
            chave = 1 + (rand() % quant);

            while (verificar(&(*lista), chave)) {
                chave = 1 + (rand() % quant);
            }
        } else if (op == 2) {
            chave = i + 1;
        }

        dado1 = 1 + (rand());

        for (int j = 0; j < TAM; j++) {
            dado2[j] = ('a' + (rand() % 26));
        }

        dado.chave = chave;
        dado.dado1 = dado1;
        for (int j = 0; j < TAM; j++) {
            dado.dado2[j] = dado2[j];
        }

        inserirElemento(&(*lista), dado);

        delete dado2;
    }

    cout << "\nLista Preenchida!";
}

void menu() {
    int op, quant, escolha;
    string tipo, nome;

    ListaEncadeada lista;
    criarLista(&lista);

    aponta p, r;

    Elemento *elemento = (Elemento *) malloc(sizeof (Elemento));

inicio:
    do {
        cout << "\n\nInforme uma escolha:\n";
        cout << "\n1. Gerar chaves de entrada aleat?ias";
        cout << "\n2. Gerar chaves de entrada ordenada.";
        cout << "\n3. Exibir chaves geradas.";
        cout << "\n4. Escrever um arquivo com as chaves geradas.";
        cout << "\n5. Ler arquivo de entrada com chaves";
        cout << "\n6. Realizar uma pesquisa";
        cout << "\n0. Sair do programa.";
        cout << "\n\nEscolha: ";
        cin >> op;

        //  Linux:
        system("clear");

        //  Windows
        //  system("cls");

		elemento = lista.primeiro;
				
        switch (op) {
            case 1:
                criarLista(&lista);
                cout << "\nInforme a quantidade de chaves a ser geradas: ";
                cin >> quant;
                if (quant <= 0) {
                    cout << "\nQuantidade informada inv?ida!\n";
                    goto inicio;
                }
                gerarchaves(&lista, quant, op);
                tipo = ("Aleatorio-");
                escolha = 1;
                break;
 	    case 2:
                criarLista(&lista);
                cout << "\nInforme a quantidade de chaves a ser geradas: ";
                cin >> quant;
                if (quant <= 0) {
                    cout << "\nQuantidade informada inv?ida!\n";
                    goto inicio;
                }
                gerarchaves(&lista, quant, op);
                tipo = ("Ordenado-");
                escolha = 2;
                break;
            case 3:
                exibeLista(lista, escolha);
                break;
            case 4:
                escrevearquivo(&lista, quant, tipo);
                cout << "\nArquivo escrito!";
                break;
			case 5:
                criarLista(&lista);
                cout << "\nInforme o nome do arquivo: ";
                cin.ignore();
                getline(cin, nome);
                lerarquivo(&lista, nome);
                escolha = 3;
                break;
            case 6:
                if (lista.primeiro == NULL) {
                    cout << "\nLista Inv?ida!\n";
                    goto inicio;
                } else {
                    cout << "\nInicializando . . .";
                    iniciarArvore(&(p));
					while (elemento != NULL) {
                        insereAVN(elemento->info, &(p));
					    elemento = elemento->proximo;
                    }
					
					elemento = lista.primeiro;
                    iniciarArvore(&(r));
                    cout << "\nArvore Iniciada!";
                    while (elemento != NULL) {
					    insereAVL(elemento->info, &(r));
                        balancear(&(r));
                        atualizar(&(r));
                        elemento = elemento->proximo;
                    }
                    cout << "\nRaiz da AVN: " << p->registro.chave;
                    cout << "\nRaiz da AVL: " << r->registro.chave;
                    menubusca(&lista, &p, &r);
                    //  exibirEmOrdem(&(r));
                }
                break;
            case 0:
                cout << "\n\n";
                break;
            default:
                cout << "\nOpçãoo informada inválida!\n";
                goto inicio;
                break;
        }
    } while (op != 0);
	
    free(elemento);
}

int main() {
    menu();
	
    cout << "\nSaída com sucesso!\n\n\n";
    return 0;
}
First hint: Always code in English.
First fact: If one sees a code in a language he doesn't know, most likely he won't even bother trying to understand it.
Second fact: Spanish isn't a well known language across the world like English may be.
Segmentation fault is a runtime error. However, your code doesn't compile
foo.cpp: In function ‘void lerarquivo(ListaEncadeada*, std::__cxx11::string)’:
foo.cpp:99:7: error: expected ‘;’ before ‘como’
foo.cpp: In function ‘void gerarchaves(ListaEncadeada*, int, int)’:
foo.cpp:164:9: error: ‘inserirElemento’ was not declared in this scope
foo.cpp: In function ‘void menu()’:
foo.cpp:177:5: error: ‘criarLista’ was not declared in this scope
foo.cpp:230:17: error: ‘exibeLista’ was not declared in this scope
foo.cpp:233:17: error: ‘escrevearquivo’ was not declared in this scope
foo.cpp:260:10: error: ‘insereAVL’ was not declared in this scope
foo.cpp:261:25: error: ‘balancear’ was not declared in this scope
foo.cpp:262:25: error: ‘atualizar’ was not declared in this scope
foo.cpp:267:21: error: ‘menubusca’ was not declared in this scope
please provide a testcase that does reproduce your issue.
Also, provide an example input and expected output.


barnack, that ain't Spanish.
Here is my complete code:
https://drive.google.com/open?id=1XVnOvpfMNN_agfesPlg2ecNVLMEJ2RsU


The data consists of:
key, data1, data2

Link of an input file:
https://drive.google.com/open?id=12LqmY655nrTjixVu-_s3T76mpCDhHPFX
code is code. The print statements and variable names don't change looking for a blown pointer. Given the compile fail above and the c-strings... well, I would have to suspect a messed up string; its VERY easy to sprintf into a string that is too short for one common example.

also the includes are all messed up. use ctime, cstring, string.h is cstring but the c version so 2 copies of the same one may make trouble, cstdlib as well. Using namespace std is also frowned upon now, best to std:: everything.

The best advice I can give right now is to start over and use strings. If you are not able to do that for whatever reason, then you will need to add print statements or step with a debugger to find the line that crashes and then figure out what it did wrong with a pointer.
you are mixing new[]/delete[] with new/delete and malloc()/free()
if allocated with new[] you must deallocate with delete[]
if allocated with new you must deallocate with delete
if allocated with malloc() you must deallocate with free()

Also, aponta *aux = (aponta *) malloc(sizeof (TipoNo)); //aponta = TipoNo* is egregious.
you are creating a pointer dynamically, wich, of course, you free in the same scope.
and the size is incorrect.
I thought with
type* variable = malloc(sizeof(type));
doing
free(variable)
or
delete variable
were equivalent, as well as with
type* variable = malloc(n * sizeof(type));
doing
free(variable)
or
delete[] variable
were.

But i Always used free with malloc and delete with new for readability purposes so i never tested mixing them. Can you tell me what's the difference in what actoually happens to the memory?
Topic archived. No new replies allowed.