Segmentation fault (core dumped)

I don't know why, but there's an error in my program, I can't see anything wrong with my code.
I compiled the program via terminal: g++ *.cc -I. -o programa and the code where the error stop the program is:
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
#include <iostream>
#include <string.h>
#include <sys/time.h>
#include <ctime>
#include <Arvore.h>
#include <Logradouro.h>
#include <cstdlib>
#include <fstream>

#define BUFFER_LENGTH 256

using namespace std;

int main(int a, char **v) {
	if(a < 2) {
		cout << "Você deve passar o nome do arquivo como parâmetro na chamada do programa!";
		return 0;
	}
	
	ifstream arquivo(v[1]);
	ofstream saida("dados.dat");
	
	char buffer[BUFFER_LENGTH];
	
	int p, cep = 0, n = 0;
	char *nome;
	
	timeval *inicio, *fim;
	double tempo;
	
	Arvore arv;
	
	bool d = false;
	int i = 0;
	do {
		arquivo.getline(buffer, BUFFER_LENGTH);
	 	
		nome = strtok(buffer, "|");
		
		if(buffer[0] != 0) cep = atoi(strtok(0, "|"));
		
		gettimeofday(inicio, 0);
		
		cout << "Preconstruct" << endl;
		// Here the program stops
		Logradouro *l = new Logradouro();
		cout << "Posconstruct" << endl;
		l->nome = nome;
		l->cep = cep;
		
		arv.inserir(l);
		
		gettimeofday(fim, 0);
				
		tempo = fim->tv_usec - inicio->tv_usec;
		
		saida << cep << " " << tempo << endl;
		
		n++;
	} while(!arquivo.eof());
	
	system("gnuplot -p \"comandos.cmd\"");
}

The Logradouro class header file:
1
2
3
4
5
6
7
8
9
10
11
12
13
#ifndef _LOGRADOURO_H_
#define _LOGRADOURO_H_

class Logradouro {
	public:
		int cep;
		char *nome;
		
		Logradouro();
		virtual ~Logradouro();
};

#endif 

The constructor of Logradouro is:
1
2
3
4
Logradouro::Logradouro() {
	cep = 0;
	nome = 0;
}

and the output of the program is:
...
Preconstruct
Segmentation fault (core dumped)
Last edited on
I see no error. Post a fully compilable example.
1
2
3
timeval *inicio, *fim;
//...
gettimeofday(inicio, 0);
`inicio' is uninitialized.
You should do
1
2
3
timeval inicio, fin; //objects, no pointers.
//...
gettimeofday(&inicio, 0);



Also, `buffer' will change its content in the next iteration, so `Logradouro::name' will have garbage


By the way, your example does not compile.

Thank you ne555, it worked here after the change you proposed. I also fixed the buffer problem by allocating a new char buffer and using the strcpy function.
Topic archived. No new replies allowed.