简体   繁体   中英

Segmentation fault after value assignment to pointer in C

There is code:

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);
}

The program falls with segmentation fault on third stroke List **current = (*previous) -> next (I checked it with printfs).

CLion debuggers says Exception: EXC_BAD_ACCESS (code=1, address=0x113d349e2)

If I do printf("address = %d\n", &((*previous) -> next)); it gives me the address.

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");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM