我试图创建一个矩阵计算器,当我尝试使用逆函数时,我得到一个错误说"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("%ft", 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"
当您将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