C中我的链表计数功能的地址边界错误

Tom*_*oli 2 c memory-management linked-list

我正在实现一个链接列表库来自学C.除了迭代之外,我已经把大多数事情都很好地工作了,迭代用于我所做的长度函数.这是用于列表的结构

typedef struct ListNode ListNode;
typedef struct List List;

struct ListNode {
    void *val;
    ListNode *next;
};

struct List {
    ListNode *head;
};
Run Code Online (Sandbox Code Playgroud)

我还有一些用于操作列表的其他函数,即创建,推送和弹出功能.如果重要,这是创建函数:

List *list_create(){
    List *list = malloc(sizeof *list);
    return list;
}
Run Code Online (Sandbox Code Playgroud)

不过,这是有问题的功能:

int list_length(List *list){
    ListNode *current = list->head;
    int count = 0;

    // Iterate through the list, adding to the count
    while(current != NULL){
        count++;
        current = current->next;
    }

    return count;
}
Run Code Online (Sandbox Code Playgroud)

出于某种原因,当它到达最后一次迭代时,while谓词不起作用,而是我得到以下错误:

Job 1, './linked_list ' terminated by signal SIGSEGV (Address boundary error)
Run Code Online (Sandbox Code Playgroud)

有什么事情表明我做错了吗?您可以在https://github.com/tominated/linked_list找到所有(不完全正常)的代码

sim*_*onc 5

list_create没有head初始化. list_push(在你的github代码中)创建一个新项并设置head为它的next指针.当您遍历列表时,最后一项指向此未初始化的指针而不是指向NULL.从现在开始,你将进入未定义的行为; 机会很高,你很快就会得到一个SIGSEGV.

修复很简单 - 您只需在创建列表时设置head即可NULL.

List *list_create(){
    List *list = malloc(sizeof *list);
    if (list != NULL) {
        list->head = NULL;
    }
    return list;
}
Run Code Online (Sandbox Code Playgroud)