简体   繁体   中英

Getting Segmentation Fault in C++, but why?

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.

 q = p;
        while(q -> link != NULL){
            q = q -> link;
        }
        t = new data;
        t -> city = cityName;
        t -> latitude = lat;
        t -> longitude = lon;
        q -> link = t;

This is the error am actually getting in console:

line 33: 2219 Segmentation fault    sh "${SHFILE}"

In the else clause in Database::add , you do not set t->link = NULL , so it is uninitialized.

You should add a constructor for data that initializes its members, or use the value-initializing new to ensure that everything is initialized correctly:

t = new data(); // note the parentheses

It's possible that it's because when you're adding a new node to the end of the list:

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;
}

you're not setting t->link = NULL; .

You are not setting Database::data::link to NULL in Database::add :

    t = new data;
    t -> city = cityName;
    t -> latitude = lat;
    t -> longitude = lon;
    t -> link = NULL;

EDIT : I would add a constructor for Database::data to initialize the various members. Something like:

class Database {
    struct data {
        data(): latitude(0.0), longitude(0.0), link(NULL) {}
        ...
    };
    ...
 };

Then you do not have uninitialized memory to worry about.

Compile with -g as an argument to g++

Then from command line "gdb (binary name)"

inside gdb, "run" and it will execute until the fault

type "bt" to see a stack trace

There may be other issues but here's one:

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;
}

You never set t->link to null and therefore it's filled with junk.

You need to assign t's link to NULL:

else{
    q = p;
    while(q -> link != NULL){
        q = q -> link;
    }
    t = new data;
    t -> city = cityName;
    t -> latitude = lat;
    t -> longitude = lon;
    t -> link = NULL; // add this
    q -> link = t;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM