我正在嘗試創建一個矩陣計算器,當我嘗試使用反函式時,我收到一條錯誤訊息,提示“malloc():損壞的頂部大小”。我不知道這個錯誤是什么意思以及如何修復它。
這是我的代碼:
double** inverse(double *mat[], int n){
//identity matrix
double **I = malloc(sizeof(double*) * n);
for (int i=0; i<n; i ) I[i] = malloc(sizeof(double) * n);
for(int i=0; i<n; i ){
for(int j=0; j<n; j ){
if(i==j){
I[i][j] = 1;
}else{
I[i][j] = 0;
}
}
}
double f = 0.0;
double sub = 0.0;
for(int p=0; p<n; n ){
f = mat[p][p];
for(int x=0; x<n; x ){
mat[p][x] = mat[p][x] / f;
I[p][x] = I[p][x] / f; (line 45)
}
for(int i=p 1; i<n; i ){
f = mat[i][p]; (line 48)
for(int x=0; x<n; x ){
sub = mat[p][x] * f;
mat[i][x] = mat[i][x] - sub; (line 51)
sub = I[p][x] * f;
I[i][x] = I[i][x] - sub; (line 54)
}
}
}
for(int p=n-1; p>=0; p--){
for(int i=p-1; i>=0; i--){
f = mat[i][p];
for(int x=0; x<n; x ){
sub = mat[p][x] * f;
mat[i][x] = mat[i][x] - sub;
sub = I[p][x] * f;
I[i][x] = I[i][x] - sub;
}
}
}
//return I;
printf("I:\n");
for(int i=0; i<n; i ){
for(int j=0; j<n; j ){
printf("%f ",I[i][j]);
}
printf("\n");
}
//free
for (int i=0; i<n; i ) free(I[i]);
free(I);
}
void multiply(double *mat1[], double *mat2[], int R1, int C1, int R2, int C2, double *rslt[]) {
for (int i = 0; i < R1; i ) {
for (int j = 0; j < C2; j ) {
rslt[i][j] = 0;
for (int k = 0; k < R2; k ) {
rslt[i][j] = mat1[i][k] * mat2[k][j];
}
printf("%f\t", rslt[i][j]);
}
printf("\n");
}
//return rslt;
}
int main(){
double **rslt = malloc(sizeof(double*) * n);
for (int i=0; i<n; i ) rslt[i] = malloc(sizeof(double) * (k 1));
multiply(x,t,n,k 1,k 1,n,rslt);
/* x and t are matrices, n=7, k 1=5,(these are the matrix dimensions for x, and the opposite are the matrix dimensions for t) */
/* the variables in the call to multiply(x and t are matrices, n and k 1 are
matrix dimensions, and rslt stores the result) are declared and cause no errors*/
/* the code works with no errors upto this point*/
/* rslt is the resulting matrix after the call to the multiply function
and n is the matrix dimensions */
inverse(rslt,n);
}
我試圖在兩個矩陣相乘后找到逆。該代碼使用“rslt”矩陣來保存乘積并呼叫反函式。乘法函式作業得很好,我只在呼叫“inverse()”后才收到錯誤。
運行 valgrind 后,它告訴我錯誤發生在反函式中。當我嘗試訪問矩陣時,它似乎在 for 回圈中多次發生。它說泄漏在第 45、48、51 和 54 行(我指定了它們在上面的哪一行)。valgrind 顯示的特定錯誤是“大小 8 的無效讀取”和“大小 8 的無效寫入”。
uj5u.com熱心網友回復:
當您將 R1xC1 矩陣與 R2xC2(其中 C1 必須等于 R2)相乘時,您將得到一個 R1xC2 矩陣。
但是你不會為結果分配它。
for (int i=0; i<n; i ) rslt[i] = malloc(sizeof(double) * (k 1))
multiply(x,t,n,k 1,k 1,n,rslt); ^^^^^
^ ^ wrong
R1 C2
所以在這里
void multiply(double *mat1[], double *mat2[], int R1, int C1, int R2, int C2, double *rslt[]) {
for (int i = 0; i < R1; i ) {
for (int j = 0; j < C2; j ) {
rslt[i][j] = 0;
您在分配的記憶體之外寫入(因為n大于k 1)。
你想做
for (int i=0; i<n; i ) rslt[i] = malloc(sizeof(double) * n)
^
notice
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/336481.html
