簡體   English   中英

分段錯誤,我不知道是什么原因造成的

[英]Segmentation fault and I don't know what's causing it

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 編譯並運行程序的 output。 不理想。

該錯誤似乎涉及下面的代碼。

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 == NULL時,試圖將cur設置為cur->next的外部循環導致了段錯誤。 是否可以重建循環以避免這種情況? (我想到了一個 do-while 循環,但沒有成功)

避免這種情況的唯一方法是將語句包含在 if 語句中嗎?

我已經嘗試了一些方法來解決這個問題。 我理解為什么它首先失敗了,但是考慮到下面的 output,它仍然失敗:

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()在附近給 output 嗎? 甚至在故障發生之前,分段錯誤就以某種方式阻止它運行。

首先,我稍微修正了您的縮進並添加了一些注釋。

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

隨后的取消引用嘗試是段錯誤。

問題很可能出在第二個cur = cur->next; ,在while循環之后 - 在這一點上,循環保證cur == NULL

我不確定您在 function 中要做什么(示例中是否省略了一些代碼?),所以目前真的沒有建議。

此外,正如您的編譯器警告所示,function 沒有返回任何內容,即使它已聲明這樣做。 我會再次假設這是因為出於問題示例的目的而刪除了某些內容,但是您的編譯器也再次抱怨。 任何使用 function 應該返回的調用者都會感到驚訝。 這個驚喜也可能是一個段錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM