繁体   English   中英

fortran LAPACK例程中的分段错误

[英]Segmentation error in fortran LAPACK routine

我正在尝试使用Fortran 95使用LAPACK库运行一个简单程序。我正在将线性方程组求解为: Ax=B

A = [4 -2 3]
    [1 3 -4]
    [3 1 2]

B=[ 1
   -7
   5]

x是解向量

解决方法是

x = [-1
     2
     3]

这是代码。 我正在使用两个子例程: SGETRFSGETRS 第一个函数SGETRF计算矩阵的LU分解,第二个子例程求解方程组。

program main
implicit none

integer :: i,j,info1,info2
integer :: neqn ! number of equations
real,dimension(3,3) :: coeff
real,dimension (3,1) :: lhs
real,dimension (3,1) :: ipiv

neqn=3

coeff = reshape( (/4,1,3,-2,3,1,3,-4,2/),(/3,3/))
lhs = reshape ( (/1,-7,5/),(/3,1/) )

call SGETRF (neqn,1,coeff,neqn,ipiv,infO1)
        if (info1==0) then
            call SGETRS ('N',neqn,1,coeff,neqn,ipiv,lhs,neqn,info2) !Error
        else
        end if

write (*,*) 'Answer: '
        do j=1,neqn,1
            write (*,100) lhs(j,1)
            100 format (F12.5,' ,')
        end do

        write (*,100) (lhs)

end program

根据LAPACK文档SGETRF,在我的情况下, M=neqn=3, N=1, A=coeff, LDA=3我将程序编译为gfortran main.f95 -o main -fcheck=all -llapack而我得到了错误:

Program received signal SIGSEGV: Segmentation fault - invalid memory reference.

Backtrace for this error:
#0  0x7F758C3B3777
#1  0x7F758C3B3D7E
#2  0x7F758C00BD3F
#3  0x7F758CA2F3EF
#4  0x7F758C9BE8ED
#5  0x400AE0 in MAIN__ at main.f95:19
Segmentation fault (core dumped)

第19行call SGETRS ('N',neqn,1,coeff,neqn,ipiv,lhs,neqn,info2)我不明白为什么会有错误。 有任何想法或意见吗?

您的错误是由SGETRF的第二个参数引起的。 此参数是coeff的第二维,因此应为3neqn

为了详细说明Stefan的正确答案,这里是对代码的修改。 我相信,通过针对LAPACK规范进行仔细编程(例如ipiv数组应为rank-1 Integer )并避免使用过多的文字常量,可以消除一些潜在的错误:

Program main
  Implicit None
  Integer, Parameter :: neqn = 3, nrhs = 1
  Integer :: info
  Real :: coeff(neqn, neqn)
  Real :: lhs(neqn, nrhs)
  Integer :: ipiv(neqn)
  coeff = reshape([4,1,3,-2,3,1,3,-4,2], shape(coeff))
  lhs = reshape([1,-7,5], shape(lhs))
  Call sgetrf(neqn, size(coeff,2), coeff, size(coeff,1), ipiv, info)
  If (info==0) Then
    Call sgetrs('N', neqn, size(lhs,2), coeff, size(coeff,1), ipiv, lhs, &
      size(lhs,1), info)
    If (info==0) Then
      Write (*, *) 'Answer: '
      Write (*, *)(lhs)
    End If
  End If
End Program

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM