C 中的 int 链表抛出分段错误

evi*_*vie 0 c struct linked-list doubly-linked-list function-definition

插入到我的链接列表中会导致分段错误,我不确定为什么。这是一个 int 链表。它有时有效,有时则无效。我看不出哪里会出错?也许这与我创建新链表的时间有关。由于链接列表插入最后一个方法在文件读取期间起作用,但在我创建新列表时不起作用。

LinkedList* createLinkedList()
{
    LinkedList* list;

    list = (LinkedList*)malloc(sizeof(LinkedList));
    list->head = NULL;
    list->tail = NULL;
    list->length = 0;

    #ifdef DEBUG
    printf("Linked list. Creation of list complete. Checking list length. %d \n", list->length);
    #endif

    return list;
}

void insertLast(LinkedList* list, int entry)
{
    Node* newNode = (Node*)malloc(sizeof(Node));
    newNode->data = entry;

    /*If list is empty*/
    if(list->length == 0)
    {
        list->head = newNode;
        list->tail = newNode;
    }
    else
    {
        newNode->prev = list->tail;
        /*if this is the second item in the list*/
        if(list->length == 1)
        {
            list->head->next = newNode;
        }
        else
        {
            list->tail->next = newNode;
        }
    }
    
    list -> tail = newNode;
    list->length++;
    #ifdef DEBUG
    printf("Linked List. Insert last complete. Checking list length. %d\n", list->length);
    #endif
}
Run Code Online (Sandbox Code Playgroud)

这有效

int main (void)
{
    LinkedList* list = createLinkedList();
    insertLast(list, 1);
}
Run Code Online (Sandbox Code Playgroud)

但这并不

int shortestSeekTimeFirst(LinkedList* list)
{
    LinkedList* usedDisks = createLinkedList();

    int data = list->head->data;
    insertLast(usedDisks, data);
    insertLast(usedDisks, list->head->next->data);
}
Run Code Online (Sandbox Code Playgroud)

Wil*_*hey 5

您永远不想盲目地取消引用可能是的指针NULL

shortestSeekTimeFirst()您直接访问list->head->next->data而不检查任何指针是否有效的情况下,因此如果listlist->head,甚至list->head->nextNULL您的程序将出现段错误。