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

C++结构体数组出现Segmentation fault问题求助

问题

尝试初始化结构体数组时遇到Segmentation fault(段错误),原本期望结构体数组能被初始化为NULL,请问该错误的原因是什么?

#include<stdlib.h>
#include<string.h>
#include<iostream>
using namespace std;
struct node{
        string data;
        int index;
        node(string data,int index):data(data),index(index){}
};
struct node **init_array(int n){
        struct node **array=(struct node **)malloc(n*sizeof(struct node *));
        for(int i=0;i<n;i++)
                *(array+i)=NULL;
        return(array);
}
struct node *init_node(string data,int index){
        struct node *t=(struct node *)malloc(sizeof(struct node));
        t->data=data;
        t->index=index;
        return(t);
}
int main(){
        node **array=init_array(5);
        *(array+0)=init_node("Debal",23);
        *(array+1)=init_node("Debdut",24);
        *(array+2)=init_node("Debojyoti",22);
        *(array+3)=init_node("Ditsa",29);
        *(array+4)=init_node("Divyani",10);
        cout << (*(array+3))->index;
}
解答

段错误的核心原因是混用C的malloc和C++的对象成员:

  • node结构体包含std::string成员,这是一个C++对象,必须通过构造函数完成内部状态初始化(比如管理动态内存的指针、容量等)。
  • 但init_node中用malloc分配内存时,只会分配原始字节空间,不会调用std::string的构造函数,导致t->data是一个未初始化的无效对象。
  • 执行t->data=data;时,实际是调用std::string的赋值运算符,但此时左边的t->data没有被正确构造,操作无效内存直接触发段错误。

修复方案

有两种常见的正确写法:

1. 用C++的new替代malloc

new会自动调用结构体的构造函数,完成成员初始化:

struct node *init_node(string data,int index){
    struct node *t = new node(data, index); // 直接调用自定义构造函数
    return t;
}

注意释放内存时要对应使用delete,而非free。

2. 坚持用malloc则手动调用构造函数

需要使用定位new初始化已分配的内存:

#include <new> // 必须包含该头文件

struct node *init_node(string data,int index){
    struct node *t = (struct node *)malloc(sizeof(struct node));
    new(t) node(data, index); // 在已分配的内存上调用构造函数
    return t;
}

这种方式需要注意,释放内存前要手动调用析构函数:t->~node(); free(t);,否则会造成内存泄漏。

另外,init_array里用malloc是没问题的,因为它仅分配指针数组,每个元素是指针类型,不需要构造函数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 01:05:22