【问题标题】:Segmentation fault (core dumped) on Ubuntu with matrix functions on C++Ubuntu上的分段错误(核心转储)与C++上的矩阵函数
【发布时间】:2013-06-06 15:46:51
【问题描述】:

我正在尝试用 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);
}

但效果不佳。

有谁知道我哪里不对?

【问题讨论】:

  • C++ 默认是传值方式。
  • 所有内存问题的答案:valgrind.
  • 您最好编写一个简单的矩阵类,该类可复制、可分配和可交换(如果您支持 C++11,则可以移动)。 ** 这个东西很脆弱。

标签: c++ matrix segmentation-fault dynamic-allocation


【解决方案1】:

您目前正在将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];
}

【讨论】:

    【解决方案2】:

    需要在参数列表中传递double ***,在调用中发送&amp;MM的地址)。没有它,你的M 没有矩阵,你会在不同的函数中得到段错误。

    【讨论】:

      【解决方案3】:

      既然你在写 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"!
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-05
        • 2020-09-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多