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

VSCode运行C语言程序时在free(temp)语句处卡住的问题求助

链表删除操作的内存错误分析与修复

问题现象

终端输入待删除的节点位置后,程序卡在free(temp)语句处,需点击两次“Continue”才能继续执行。

代码中的两处关键错误

  1. Insert函数内存分配错误
    在Insert函数中,malloc的参数错误使用sizeof(struct Node*),仅分配了一个指针的内存空间,而非整个链表节点的大小。内存分配不足会导致后续对节点的读写操作越界,破坏内存结构。
    错误代码:

    struct Node* temp = (struct Node*)malloc(sizeof(struct Node*));
    
  2. Delete函数释放错误节点
    在Delete函数的非首节点删除逻辑中,最后释放的是temp(当前遍历到的前驱节点),而非temp1(真正要删除的目标节点)。释放错误节点会导致链表结构断裂,触发内存访问异常。
    错误代码:

    free(temp); 
    

修正后的完整代码

#include <stdio.h>
#include <stdlib.h>
struct Node{  
    int data;
    struct Node* next;
};

struct Node* head;

void Insert(int n){
    // 修正:分配整个Node结构体的内存
    struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
    temp->data = n;
    temp->next = head;
    head = temp;
}

void Delete(int z){
    struct Node* temp = head;

    if(z == 1){
        head = temp->next;
        free(temp);
        return;
    }
    int i;
    for(i=0;i<z-2;i++){
        temp = temp->next;
    }

    struct Node* temp1;
    temp1 = temp->next;
    temp->next = temp1->next;
    // 修正:释放真正要删除的temp1节点
    free(temp1); 
}

void print(){
    printf("List is:");
    int x;
    struct Node* temp1;
    temp1 = head;
    while(temp1 != NULL){
         x = temp1->data;
         printf("%d ",x);
         temp1 = temp1->next;
    }
   printf("\n");
}

int main()
{
    head = NULL;
    int k;
    Insert(2);
    Insert(5);
    Insert(4);
    Insert(7);
    Insert(0);
    Insert(8);
    Insert(5);
    Insert(6);
    print();
    printf("you want to delete:");
    scanf("%d",&k);
    Delete(k);
    print();
    system("pause");

    return 0;
}

额外建议

  • 增加输入合法性检查:比如用户输入的k不能小于1,也不能超过链表的实际长度,避免非法输入导致的链表越界访问。
  • 养成内存分配后检查的习惯:每次malloc后判断返回值是否为NULL,防止内存分配失败引发后续错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 04:15:36