You need to enable JavaScript to run this app. C++矩阵类setter函数赋值异常,调用后后续语句未执行
优惠活动
大模型
产品
解决方案
定价
更多

C++矩阵类setter函数赋值异常,调用后后续语句未执行

问题根因

你的程序是触发了空指针写入的段错误直接崩溃,导致set_values后的打印语句没机会执行,具体错误点如下:

  • 你在operator+中通过默认构造函数创建了Matrix C,默认构造函数将values指针初始化为NULL,你仅调用C.setdim(rowa, colb)修改了行列数,没有给values指针分配对应的堆内存
  • 调用C.set_values(i, m)时,直接对NULL指针指向的地址赋值,触发非法内存访问,操作系统直接终止进程,后续代码无法执行

额外存在的问题

你的代码还存在C++动态内存管理的典型问题:

  • 类中包含动态分配的指针成员values,没有实现自定义的析构函数、拷贝构造函数、拷贝赋值运算符,使用默认生成的函数只会做浅拷贝,会出现内存泄漏、重复释放同一块内存的崩溃问题
  • 带参数的构造函数中,入参double* x没有被使用,属于无用参数

修复方案

1. 修改setdim方法,分配对应内存

void setdim(int m, int n){
    // 先释放原有内存避免泄漏
    if(values != nullptr) {
        delete[] values;
    }
    row = m;
    col = n;
    // 为values分配对应大小的内存
    values = new double[m * n];
}

2. 添加析构函数释放内存

~Matrix() {
    if(values != nullptr) {
        delete[] values;
        values = nullptr;
    }
}

3. 实现拷贝构造函数和拷贝赋值运算符(符合三五法则)

// 拷贝构造函数
Matrix(const Matrix& other) {
    row = other.row;
    col = other.col;
    values = new double[row * col];
    for(int i = 0; i < row * col; i++) {
        values[i] = other.values[i];
    }
}
// 拷贝赋值运算符
Matrix& operator=(const Matrix& other) {
    if(this == &other) {
        return *this;
    }
    // 释放原有内存
    if(values != nullptr) {
        delete[] values;
    }
    // 拷贝新对象的内容
    row = other.row;
    col = other.col;
    values = new double[row * col];
    for(int i = 0; i < row * col; i++) {
        values[i] = other.values[i];
    }
    return *this;
}

修复完成后运行程序,Returned from C.set_values()就可以正常打印输出了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 09:18:03