我的ANSI C链表代码出现段错误(SIGSEGV),请求排查错误
Hey there! Let's walk through your linked list code and fix those segmentation faults step by step. I'll break down the issues and show you how to fix them:
1. Broken Node Linking Logic in create() Function
In the else block of your create function, you placed p->nxt = temp inside the while loop. This messes up the chain immediately: the first iteration sets the current node's next to the new temp, then moves p to temp. The next loop check sees p->nxt is NULL and exits, leaving the rest of your nodes unconnected (and creating invalid pointer references).
Wrong code snippet:
else { p = head; while (p->nxt != NULL) { p = p->nxt; p->nxt = temp; // This is inside the loop - bad! } }
Fixed version:
else { p = head; // First traverse to the LAST node in the list while (p->nxt != NULL) { p = p->nxt; } // Now link the new node to the end p->nxt = temp; }
2. Assignment Instead of Comparison in display()
You wrote if (head = NULL) which is an assignment (sets head to NULL) instead of a check. This will incorrectly mark non-empty lists as empty, and lead to invalid pointer access later. Always use == for equality checks.
Fixed line:
if (head == NULL)
3. Spurious Semicolon in display() Loop
Your while (p != NULL); has an extra semicolon at the end. This makes the loop body empty, so the program will loop forever until p becomes a wild pointer, then crash when trying to access p->data. Remove that semicolon so the curly braces code runs as the loop body.
Fixed loop:
while (p != NULL) { printf("%d->", p->data); p = p->nxt; }
Full Corrected Code
Here's the complete working version with these fixes (plus a small touch to make the display output clearer):
#include<stdio.h> #include<stdlib.h> typedef struct node { int data; struct node *nxt; } node; node * create(int n); void display(node *head); int main() { int n = 0; node *head = NULL; printf("Enter the number of nodes\n"); scanf("%d", &n); head = create(n); display(head); return 0; } node * create(int n) { int i; node *head = NULL; node *temp = NULL; node *p = NULL; for (i = 0; i < n; i++) { temp = (node *)malloc(sizeof(node)); printf("\nEnter the value of %d node: ", i + 1); scanf("%d", &temp->data); temp->nxt = NULL; if (head == NULL) { head = temp; } else { p = head; while (p->nxt != NULL) { p = p->nxt; } p->nxt = temp; } } return head; } void display(node *head) { node *p = NULL; if (head == NULL) { printf("\nEmpty List"); } else { p = head; while (p != NULL) { printf("%d->", p->data); p = p->nxt; } printf("NULL"); // Marks the end of the linked list } }
内容的提问来源于stack exchange,提问作者Utkarsh Gajal

