Getting Segmentation Fault in C++, but why?
- by Carlos
I am getting segmentation fault in this code but i cant figure out why. I know a segmentation fault happens when a pointer is NULL, or when it points to a random memory address.
#include <iostream>
#include <fstream>
#include <cmath>
using namespace std;
//**************************** CLASS *******************************
class Database {
struct data{
string city;
float latitude, longitude;
data *link;
}*p;
public:
Database();
void display();
void add(string cityName, float lat, float lon);
private:
string cityName;
float lat, lon;
};
//************************** CLASS METHODS **************************
Database::Database() {
p = NULL;
}
void Database::add(string cityName, float lat, float lon){
data *q, *t;
if(p == NULL){
p = new data;
p -> city = cityName;
p -> latitude = lat;
p -> longitude = lon;
p -> link = NULL;
}
else{
q = p;
while(q -> link != NULL){
q = q -> link;
}
t = new data;
t -> city = cityName;
t -> latitude = lat;
t -> longitude = lon;
q -> link = t;
}
}
void Database::display()
{
data *q;
cout<<endl;
for( q = p ; q != NULL ; q = q->link )
cout << endl << q -> city;
}
//***************************** MAIN *******************************
//*** INITIALIZATION ***
Database D;
void loadDatabase();
//****** VARIABLES *****
//******* PROGRAM ******
int main() {
loadDatabase();
D.display();
}
void loadDatabase() {
int i = 0;
string cityName;
float lat, lon;
fstream city;
city.open("city.txt", ios::in);
fstream latitude;
latitude.open("lat.txt", ios::in);
fstream longitude;
longitude.open("lon.txt", ios::in);
while(!city.eof()){ //************************************
city >> cityName; //* *
latitude >> lat; //Here is where i think is the problem
longitude >> lon; //* *
D.add(cityName, lat, lon); //************************************
}
city.close();
latitude.close();
longitude.close();
}
This is the error am actually getting in console