[英]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);
}
但是,效果也不理想。
有人知道我在哪里做錯了嗎?
您當前正在將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];
}
你需要通過double ***
在參數表並發送&M
(地址M
的呼叫)。 否則,您的M
沒有矩陣,並且您會在其他函數中遇到段錯誤。
既然您正在編寫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"!
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.