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

链表添加字符串报错求助:赋值语句触发运行时崩溃

链表赋值字符串崩溃的解决办法

兄弟,你这个崩溃的核心问题太典型了——你手里的new_node是个野指针!说白了就是你只声明了一个指针变量,但根本没给它分配实际的内存空间,直接去访问它的name成员,可不就触发内存访问错误崩了嘛。

先看你代码里的疏漏:你肯定是只写了list_item *new_node;,但没调用new或者malloc给这个指针分配真正的节点内存。指针本身只是个存地址的变量,默认值是随机的,指向的是内存里的无效区域,直接赋值当然会炸。

给你修正后的完整可运行代码,关键步骤我都标出来了:

#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;

struct list_item {
    int key;
    int value;
    string name;
    list_item *next;
};

struct list {
    struct list_item *first;
};

int main() {
    // 先初始化链表头,避免野指针
    list my_list;
    my_list.first = nullptr;

    // 重点!给新节点分配内存,这步你之前肯定漏了
    list_item *new_node = new list_item();
    if (new_node == nullptr) {
        cerr << "内存分配失败,程序退出" << endl;
        return 1;
    }

    // 现在再赋值就安全了
    new_node->key = 1;
    new_node->value = 100;
    new_node->name = "hello";
    new_node->next = nullptr;

    // 把新节点挂到链表头部
    new_node->next = my_list.first;
    my_list.first = new_node;

    // 测试输出看看结果
    list_item *current = my_list.first;
    while (current != nullptr) {
        cout << "Key: " << current->key 
             << ", Value: " << current->value 
             << ", Name: " << current->name << endl;
        current = current->next;
    }

    // 记得释放内存,别搞内存泄漏
    current = my_list.first;
    while (current != nullptr) {
        list_item *temp = current;
        current = current->next;
        delete temp;
    }

    return 0;
}

再给你划几个重点:

  • 分配内存时,C++里优先用new list_item(),它会自动调用string的构造函数,帮你初始化name成员;如果用malloc的话,string的内部结构不会被正确初始化,还是容易出问题。
  • 指针声明后一定要让它指向有效的内存,要么是分配的新内存,要么是已经存在的合法节点,绝对不能用默认的野指针去访问成员。
  • 用完链表记得遍历释放每个节点的内存,养成好习惯避免内存泄漏。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 08:30:55