簡體   English   中英

對 C 中的指針賦值后的分段錯誤

[英]Segmentation fault after value assignment to pointer in C

有代碼:

void pop(int id, List *head) {
    List **previous = head;
    List **current = (*previous) -> next;

    if(head -> next == NULL && (*head).id == id) {
        free(head);
    } //if only 1 node in List

    while((**current).id != id) {
        *previous = head -> next;
        *current = previous;
    }

    (*previous) -> next = (*current) -> next;
    free(*current);
}

該程序在第三筆划List **current = (*previous) -> next (我用printfs檢查過)上出現segmentation fault

CLion 調試器說Exception: EXC_BAD_ACCESS (code=1, address=0x113d349e2)

如果我這樣做printf("address = %d\n", &((*previous) -> next)); 它給了我地址。

void delete_worker_by_id(int id, List *head) {
    List **previous = &head;
    List *current = (*previous) -> next;

    if(head -> next == NULL && (*head).id == id) {
        free(head);
        head = NULL;
    } //if only 1 node in List

    while((*current).id != id) {
        *previous = current;
        current = current -> next;
    }

    if((*current).id == id) {
        (*previous) -> next = current -> next;
        current -> next = NULL;
        free(current);
        return;
    }
    puts("No worker with this id");
}

暫無
暫無

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

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