我正试图编写一个代码,使用翻版库在C中反演一个复杂的矩阵,但是,我遇到了一个分割错误,这似乎取决于矩阵的大小N。更重要的是,每次我编译程序或触摸任何东西时,发生分段错误的大小都是不同的。这使我认为代码试图访问分配不良或被禁止的内存的某个地方。不幸的是,我不明白这是如何发生的,因为它似乎与LAPACKE函数主题相关。实际上,当函数/*MatrixComplexInv(invA,A,N);*/ (其中调用LAPACKE函数进行反演)被注释时,分割错误就不会发生。下面是可以自己编译和运行的工作代码。
#include <stdio.h>
#include <lapacke.h>
#include <complex.h>
#include <stdlib.h>
#include <math.h>
void Ctranspose( double complex *, double complex * ,int );
void MatrixComplexInv(double complex *, double complex *, int );
int main(int argc, const char * * argv) {
int i,j,k,N = 4;/*if N> bigger than a small number 4,6,7.. it gives segmentation fault*/
double complex *A = calloc(N*N,sizeof(double complex)),
*b = calloc(N*N,sizeof(double complex)),
*Ap =calloc(N*N,sizeof(double complex));
double complex *invA =calloc(N*N,sizeof(double complex));
for(i=0;i<N;i++){
for(j=0;j<N;j++){
A[i*N+j] = 1+sin(i*j)*i+I*j;
Ap[i*N+j] = 1+sin(i*j)*i+I*j;
}
}
/*Segmentation fault in this function, due to
*
LAPACKE_zgetrf(LAPACK_ROW_MAJOR, n, n, tempA , n,&n);
LAPACKE_zgetri(LAPACK_ROW_MAJOR, n, tempA , n, &n );
*
* both.
*/
MatrixComplexInv(invA,A,N);
for(i=0;i<N;i++){
for(j=0;j<N;j++){
for(k = 0;k<N;k++){
b[i*N+j]+=invA[i*N + k]*Ap[k*N + j];
}
printf("(%lf,%lf)\t", creal(b[i*N + j]),cimag(b[i*N + j]));/*tests that the result produces the inverse matrix A^{-1}A = 1*/
}
printf("\n");
}
return 0;
}
void Ctranspose( double complex *Transposed, double complex *M ,int n)
{
int i,j;
for(i=0;i<n;i++)
for(j=0;j<n;j++) Transposed[i+n*j] = M[i*n+j];
}
void MatrixComplexInv(double complex *invA, double complex *A, int n)
{
double complex *tempA = (double complex*) malloc( n*n*sizeof(double complex) );
Ctranspose(tempA,A,n);
/*SEGMENTATION HAPPEN IN THESE TWO FUNCTIONS*/
LAPACKE_zgetrf(LAPACK_ROW_MAJOR, n, n, tempA , n,&n);
LAPACKE_zgetri(LAPACK_ROW_MAJOR, n, tempA , n, &n );
Ctranspose(invA,tempA,n);
free(tempA);
}发布于 2019-02-23 10:35:44
在LAPACKE_zgetrf(LAPACK_ROW_MAJOR, n, n, tempA , n,&n);中,兹格特夫的最后一个参数指向n,一个整数。相反,论点ipiv应该是指向维度max(m,n)的整数数组的指针,用于存储枢轴索引。 --这可以解释分段错误。
为了得到正确的逆矩阵,还必须将由LAPACKE_zgetrf()计算的LAPACKE_zgetrf()作为输入提供给LAPACKE_zgetri()。
https://stackoverflow.com/questions/54837008
复制相似问题