分割错误(核心转储)在Ubuntu上使用c++上的矩阵函数

Segmentation fault (core dumped) on Ubuntu with matrix functions on C++

本文关键字:c++ 函数 Ubuntu 错误 核心 转储 分割      更新时间:2023-10-16

我正试图在c++中构建一个程序,该程序与矩阵和矩阵函数一起工作。我的代码编译正常,但当我试图执行它时,我得到消息:

段错误(信息转储)

我的代码有很多函数是这样的:

void function(double **matrix, ...) {
    //Operations with the matrix
}

我这样调用函数:

double **M;
function(M,...);

通过研究消息,我发现我需要动态分配将要使用的矩阵,因此编写了以下函数来执行此分配:

void allocMatrix(double **M, int nl, int nc) {
M = new double*[nl];
for(int i = 0; i < nl; ++i)
        M[i] = new double[nc];
}
void freeMatrix(double **M, int nl) {
for(int i = 0; i < nl; ++i)
         delete [] M[i];
delete [] M;
}

现在用这些函数,我试着调用我的其他函数,这样做:

double **M;
allocMatrix(M, numberOfLines, numberOfColumns);
function(M,...);
freeMatrix(M, numberOfLines);

然而,即使有了这个改变,我仍然得到消息"分割错误(核心转储)"。

我甚至尝试像这样分配函数内部的矩阵:

void function(double **matrix, ...) {
    allocMatrix(M, numberOfLines, numberOfColumns);
    //Operations with the matrix
    freeMatrix(M, numberOfLines);
}

但它没有那么好。

有谁知道我哪里说错了吗?

您需要在参数列表中传递double ***,在呼叫中发送&M (M的地址)。如果没有这个,您的M没有矩阵,并且您在不同的函数中得到分段故障。

您当前正在传递M的副本给allocMatrix。当函数返回时,您在这里分配的内存会泄漏。如果你想修改调用者的变量,你需要传递一个指向M的指针

double **M;
allocMatrix(&M, numberOfLines, numberOfColumns);
function(M,...);
freeMatrix(M, numberOfLines);
void allocMatrix(double ***M, int nl, int nc) {
    *M = new double*[nl];
    for(int i = 0; i < nl; ++i)
            (*M)[i] = new double[nc];
}

既然你在写c++,为什么不用vector呢?

#include <vector>
int main()
{
    // This does what your "allocMatrix" does.
    std::vector< std::vector<double> > M(numberOfLines, numberOfColumns);
    // Look Ma!  No need for a "freeMatrix"!
}