简体   繁体   English

在C ++中出现分段错误,但是为什么呢?

[英]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. 我知道当指针为NULL或指向随机内存地址时会发生分段错误。

 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. Database::addelse子句中,您未设置t->link = NULL ,因此未初始化。

You should add a constructor for data that initializes its members, or use the value-initializing new to ensure that everything is initialized correctly: 您应该为初始化其成员的data添加一个构造函数,或者使用值初始化的new来确保正确初始化所有内容:

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; 您没有设置t->link = NULL; .

You are not setting Database::data::link to NULL in Database::add : 您没有在Database::add Database :: data :: link设置为NULL

    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. 编辑 :我将为Database::data添加一个构造函数以初始化各种成员。 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++ 使用-g作为g ++的参数进行编译

Then from command line "gdb (binary name)" 然后从命令行“ gdb(二进制名称)”

inside gdb, "run" and it will execute until the fault 在gdb内,“运行”,它将执行直到故障

type "bt" to see a stack trace 输入“ bt”以查看堆栈跟踪

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. 您永远不会将t->link设置为null,因此它充满了垃圾。

You need to assign t's link to NULL: 您需要将t的链接分配为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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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