簡體   English   中英

C 鏈表分段錯誤 11

[英]C Linked List segmentation fault 11

我不斷收到這個 Segmentation Fault: 11 錯誤,我不知道為什么。

我的代碼:

typedef struct Node* NodePtr;
struct Node
{
    NodePtr next;
    void *val;
};

struct List
{
    NodePtr head;
};
typedef struct List* ListPtr;

int compare(void *one, void *two)
{
    if(*(int*)one < *(int*)two)
        return -1;
    else if(*(int*)one > *(int*)two)
        return 1;

    return 0;
}

ListPtr create()
{
    ListPtr blah = malloc(sizeof(struct List));
    memset(blah, 0, sizeof(struct List));

    return blah;
}

NodePtr scan(NodePtr head, void *obj)
{
    NodePtr previous, current;

    previous = head;
    current = head->next;      // Segmentation fault here!!

    while(current != NULL && (compare(curry->val, obj) == -1))
    {
        previous = current;
        current = current->next;
    }

    return previous;
}

int insert(ListPtr llist, void *obj)
{
    NodePtr newobj = malloc(sizeof(struct Node));
    NodePtr prevNode, nextNode;

    prevNode = search(llist->head, obj);
    nextNode = prevNode->next;

    if((nextNode == NULL) || (compare(nextNode->val, obj) != 0))
    {
        prevNode->next = newobj;
        newobj->next = nextNode;

        return 1;
    }
    else
    {
        free(newobj);
    }

    return 0;
}

我認為head沒有分配,所以我在 create 中為blah->head添加了malloc ,但仍然沒有運氣。

我認為經過一些調試后出現錯誤: current = head->next

任何幫助,將不勝感激! 感謝您的時間!

編輯:我如何調用插入:

int main(int argc, char *argv[])
{
    ListPtr list = create();

    int x = 2;
    int *p = &x;

    while(*p != 0)
    {
        printf("\nEnter a number: ");
        scanf("%d", p);

        if(*p != 0)
            insert(list, p);
    }

    return 0;
}

掃描列表時,您似乎不會檢查列表是否為空。 但是,如果沒有一個最小完整可驗證示例告訴我們您如何調用該函數,則無法確定您做了什么。

更新

現在你有了,似乎就是這樣。 您創建一個空列表並在插入函數中搜索它。 搜索函數取消引用head清零的指針,導致段錯誤。

嘗試以下操作:首先,在對指針執行任何操作之前,檢查它在每個函數中是否有效。 空列表應該在每次搜索中失敗。 其次,為了獲得最大的可移植性,您希望將head指針設置為NULL (因為NULL指針在所有實現中不一定都是位為零)。

暫無
暫無

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

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