简体   繁体   中英

Can't understand why I keep getting segmentation fault for this code

A very simple code:

typedef struct node {
    int x;
    struct node* next;
} *Node;

void advance_node(Node ptr) {
    ptr = ptr->next;
    while (ptr) {
        printf("%d\n", ptr->x);
        ptr = ptr->next;
    }
}

int main() {
    Node node1 = malloc(sizeof (*node1));
    Node node2 = malloc(sizeof (*node2));
    Node node3 = malloc(sizeof (*node3));

    node1->x = 1;
    node1->next = node2;

    node2->x = 4;
    node2->next = node3;

    node3->x = 9;
    node3->next = NULL;

    advance_node(node1);
    return 0;
}

I expect to see an output of 4 and 9, yet I keep getting a segmentation fault. Where is my mistake? This is driving me crazy.

You're probably getting a seg fault because of a NULL pointer.

You can easily protect against this in your advance_node function like so:

void advance_node(Node ptr) {
    if(!ptr) return; //protect against NULL pointer
    ptr = ptr->next;
    while (ptr) {
        printf("%d\n", ptr->x);
        ptr = ptr->next;
    }
}

I made this change and tested your code here: https://onlinegdb.com/B1endJr9E

Try declaring your struct as

typedef struct node {
    int x;
    struct node* next;
} Node;

Then use Node *node1 = malloc(sizeof (*node1));

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