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

Turbo C++中C语言双向链表莫名多出两个固定节点问题求助

双向链表在Turbo C++中出现额外节点的问题解决

问题描述

  • 使用C语言实现双向链表,通过Turbo C++编译运行时,链表会莫名出现两个固定节点,无对应添加代码
  • 相同代码在VS Code中运行正常,必须在Turbo C++环境下运行程序,更换系统后问题依旧

问题定位

核心错误出现在insatbeg函数的内存分配语句:

ptr = (struct Node *)malloc(sizeof(struct Node *));

此处错误地使用sizeof(struct Node *)(指针类型的大小)来分配内存,而非sizeof(struct Node)(结构体本身的大小)。

在Turbo C++的16位环境中,struct Node *的大小为2字节,但struct Node包含两个指针和一个int类型成员,总大小为6字节(16位环境下int占2字节)。分配的内存空间不足,导致后续对结构体成员的写入操作越界,破坏堆内存结构,进而出现额外的无效节点。

VS Code通常使用32/64位编译器,指针大小为4/8字节,虽同样存在内存分配不足问题,但内存布局差异导致未触发明显异常,本质仍属于未定义行为。

修复方案

将内存分配语句修改为:

ptr = (struct Node *)malloc(sizeof(struct Node));

该语句会为整个结构体分配足够内存,彻底避免内存越界问题。

额外优化建议

  • 移除全局变量temp,在display函数内声明局部变量,降低全局变量引发的潜在风险
  • 替换goto语句为continue,优化代码逻辑,提升可读性

修复后的完整代码

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>

struct Node
{
    struct Node *prev;
    int data;
    struct Node *next;
} *head = NULL;

void insatbeg()
{
    int item;
    struct Node *ptr = NULL;
    printf("\nEnter Item: ");
    scanf("%d", &item);
    ptr = (struct Node *)malloc(sizeof(struct Node));
    if (ptr == NULL)
        printf("\nOverflow Occured");
    else if (head == NULL)
    {
        ptr->data = item;
        ptr->next = ptr->prev = NULL;
        head = ptr;
    }
    else
    {
        ptr->prev = NULL;
        ptr->data = item;
        ptr->next = head;
        head->prev = ptr;
        head = ptr;
    }
}

void display()
{
    if (head == NULL)
        printf("\nList is Empty");
    else
    {
        struct Node *temp = head;
        while (temp != NULL)
        {
            printf("%d\t", temp->data);
            temp = temp->next;
        }
    }
}

int main()
{
    int loopvar = 1, switchvar;
    clrscr();
    while (loopvar == 1)
    {
        printf("\nEnter 1 to Insert at First");
        printf("\nEnter 2 to Display");
        printf("\nEnter: ");
        scanf("%d", &switchvar);
        switch (switchvar)
        {
        case 1:
            insatbeg();
            break;
        case 2:
            display();
            break;
        default:
            printf("\nEnter Properly: ");
            continue;
        }
        printf("\nDo You Want to Continue: ");
        scanf("%d", &loopvar);
    }
    getch();
}

内容的提问来源于stack exchange,提问作者Anurag Karthik Polamarasetty

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 17:20:58