分割错误(核心转储)在Ubuntu上使用c++上的矩阵函数
Segmentation fault (core dumped) on Ubuntu with matrix functions on C++
我正试图在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"!
}
相关文章:
- "error: no matching function for call to"构造函数错误
- 什么时候调用组成单元对象的析构函数
- 继承函数的重载解析
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- C++模板来检查友元函数的存在
- 递归函数计算序列中的平方和(并输出过程)
- 对RValue对象调用的LValue ref限定成员函数
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- 为什么使用 "this" 指针调用派生成员函数?
- 将对象数组的引用传递给函数
- 函数调用中参数的顺序重要吗
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用不带参数的函数访问结构元素
- 代码在main()中运行,但在函数中出现错误
- 内置函数可查看CPP中的成员变量
- 如何获取std::result_of函数的返回类型
- 如何在c++中为模板函数实例创建快捷方式
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗