You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

链表节点删除操作出现段错误,求问题排查与修正方案

Fixing the Segmentation Fault in Your Linked List Deletion Code

Hey there! Let's break down why your code is causing a segmentation fault and how to fix it. I've gone through your code and spotted a few key issues that are leading to the crash:

Key Issues in Your Original Code

  • Off-by-one error: The problem uses 1-based indexing for the position x, but your code treats it as 0-indexed. This means you're deleting the wrong node (or crashing) when x is 1 (the head node).
  • Missing return after head deletion: When you delete the head node, you don't return immediately. The code continues to run, trying to access a freed pointer (temp), which leads to undefined behavior like a segfault.
  • No null pointer checks: If x is larger than the length of the linked list, temp becomes NULL, and accessing temp->next causes a segfault.
  • No return statement at the end: Your function is supposed to return a Node*, but there's no return outside the initial if block. This leads to returning garbage values, which can cause crashes.

Corrected Code

Node* deleteNode(Node *head,int x) {
    // Handle deletion of the head node (1-based position)
    if(x == 1){
        Node* temp = head;
        head = head->next;
        free(temp);
        return head;
    }
    
    Node* temp = head;
    // Traverse to the node just before the one we want to delete
    for(int i=0; temp != NULL && i < x-2; ++i){
        temp = temp->next;
    }
    
    // Check if we're trying to delete a non-existent node
    if(temp == NULL || temp->next == NULL){
        return head; // Return original head if x is invalid
    }
    
    // Delete the target node
    Node* toDelete = temp->next;
    temp->next = toDelete->next;
    free(toDelete);
    
    return head;
}

Explanation of Fixes

  1. 1-based indexing adjustment: Changed the head deletion condition to x == 1 to match the problem's requirements.
  2. Immediate return after head deletion: After updating the head and freeing the old head node, we return the new head right away to avoid using the freed pointer.
  3. Null pointer safety checks: Before accessing temp->next, we verify that temp isn't NULL and that the node to delete exists. This prevents segfaults from invalid positions.
  4. Proper return statements: Added a return at the end to return the modified (or original) head pointer, ensuring the function behaves correctly in all cases.

内容的提问来源于stack exchange,提问作者Prav

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 09:06:52