分段错误,我不知道是什么导致它

时间:2011-04-29 23:55:21

标签: c null segmentation-fault

main.c:132:26: warning: "/*" within comment
main.c: In function ‘importSettings’:
main.c:152: warning: control reaches end of non-void function
main.c: In function ‘cs_init_missions’:
main.c:84: warning: control reaches end of non-void function
j@jonux:~/Projects/csgtk/c$ ./a.out 
Segmentation fault
j@jonux:~/Projects/csgtk/c$ 

这是使用-Wall编译并运行程序的输出。不理想。

错误似乎涉及以下代码。

static xmlDocPtr importSettings(char file[], GtkBuilder *builder) {
    cur = cur->xmlChildrenNode;
    while (cur != NULL) {
        if(xmlStrEqual(cur->name, (const xmlChar *) "options")) {
            cur = cur->xmlChildrenNode;
            while (cur != NULL) {
                cur = cur->next; 
            }
        }
        cur = cur->next;// <- Segfault is here
    }
}

cur导致段错误时,外环似乎试图将cur->next设置为cur == NULL。是否有可能重建循环以避免这种情况? (我想到了一个do-while循环,但没有成功)

避免这种情况的唯一方法是将语句包含在if语句中吗?

我已经尝试过修复问题的方法。我理解为什么它首先失败了,但鉴于下面的输出它仍然失败:

static xmlDocPtr importSettings(char file[], GtkBuilder *builder){
        if (file == NULL) {
            file = "CsSettings.xml";
        }
        //commented stuff here
        settingsTree = xmlParseFile(file);
        //commented stuff here
        cur = xmlDocGetRootElement(settingsTree);
        cur = cur->xmlChildrenNode;
        while (cur != NULL){

            if(xmlStrEqual(cur->name, (const xmlChar *) "options")){ 
                cur = cur->xmlChildrenNode;
                while (cur != NULL){
        //commented stuff here
                    if(cur->next == NULL)
                        cur = cur->parent;
                    else
                        cur = cur->next;

                }
            }
            cur = cur->next;
        }
}

有没有办法让printf()在这附近输出?即使在故障发生之前,分段故障也会以某种方式阻止它运行。

2 个答案:

答案 0 :(得分:5)

首先,我稍微修改了缩进并添加了一些注释。

static xmlDocPtr importSettings(char file[], GtkBuilder *builder){
    cur = cur->xmlChildrenNode;
    while (cur != NULL){
        if(xmlStrEqual(cur->name, (const xmlChar *) "options")){
            cur = cur->xmlChildrenNode;
            while (cur != NULL){
                cur = cur->next;
            }
            //at this point, cur == NULL
        }
        cur = cur->next;//seg fault here
    }
}

问题是当if语句为真时,您会运行第二个while循环,使cur等于NULL

随后的取消引用尝试是seg错误。

答案 1 :(得分:1)

问题很可能出现在cur = cur->next;循环之后的第二个while - 此时循环已经保证cur == NULL

我不确定你在这个函数中想要做什么(有一些代码被省略了吗?),所以暂时没有建议。

此外,正如您的编译器警告所示,即使声明这样做,函数也不会返回任何内容。我会再次假设这是因为在问题中为了示例的目的删除了某些东西,但是你的编译器也在抱怨。任何使用函数应该返回的调用者都会感到惊讶。这个惊喜也可能是一个段落错误。

相关问题