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

C++实现每节点存4位数字的双向链表运行直接退出问题排查

问题原因

  • 第一个严重问题:你使用malloc分配包含std::string成员的Node结构体,属于未定义行为。malloc只会申请原始内存空间,不会调用结构体内部string成员的构造函数,后续给newnode->data赋值时会操作未初始化的内存,大概率直接导致程序异常退出。
  • 第二个问题:你在输出字符串长度后调用了getch(),该函数会阻塞程序等待用户按下任意按键才会继续执行后续的链表插入、打印逻辑。如果你运行时输完数字回车后没有按其他按键,部分运行环境可能会直接结束程序,看不到后续输出。
  • 补充说明:你当前用的是头插法插入节点,最终输出的链表内容和原字符串顺序是相反的,如果需要和原输入顺序一致,可以改成尾插法实现。

修复方案

  1. 将malloc替换为C++的new关键字,分配内存时会自动调用Node以及内部string成员的构造函数:
// 原有错误代码
struct Node* newnode = (struct Node*)malloc(sizeof(struct Node));
// 替换为
struct Node* newnode = new Node;
  1. 把getch()移动到main函数末尾、return 0之前,这样程序完成所有逻辑输出后再等待按键退出,避免中间阻塞。

修复后完整可运行代码

#include <iostream>
#include <string>
#include <conio.h>

using namespace std;
struct Node {
  string data;
  struct Node* prev;
  struct Node* next;
};
struct Node* head = NULL;
void insert(string newdata) {
  struct Node* newnode = new Node;
  newnode->data = newdata;
  newnode->prev = NULL;
  newnode->next = head;
  if (head != NULL)
    head->prev = newnode;
  head = newnode;
  cout << "\nNode inserted";
}

void display() {
  struct Node* ptr;
  ptr = head;
  while (ptr != NULL) {
    cout << ptr->data << " ";
    ptr = ptr->next;
  }
}
int main() {
  string n1, temp;
  cout << "Enter the number\n";
  cin >> n1;
  int len, i;
  len = n1.size();
  cout << "\n Length is " << len;

  for (i = 0; i < len; i = i + 4) {
    insert(n1.substr(i, 4));
  }

  cout << "\nThe doubly linked list is: ";
  display();
  getch();
  return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 08:06:06