我用gfortran编译了一个fortran 90程序,该程序以我想要的方式构建了可扩展的3D阵列。运行时,出现以下错误:
Program received signal SIGSEGV: Segmentation fault - invalid memory reference.
Backtrace for this error:
#0 0x10542ee42
#1 0x10542f60e
#2 0x7fff8d7895a9
#3 0x10542575e
#4 0x105425975
#5 0x105425d0e
Segmentation fault: 11
我相信这是大型3D阵列的内存问题,因为如果减小尺寸,它可以工作,但是仍然可以解决此问题吗?这是我的代码:
PROGRAM phantomtest
IMPLICIT NONE
INTEGER, PARAMETER:: columns=34, rows=34, diags=((4*columns)-6), m=(4*columns)-6+(2*columns)
REAL, ALLOCATABLE, DIMENSION(:,:,:)::phantom
INTEGER :: i, j, k
CHARACTER (LEN=3) :: nstring, nullstring=''
ALLOCATE(phantom(columns,rows,m))
phantom=0
CALL Phantom_Making(phantom,columns,rows,diags,m)
WRITE(nstring,FMT="(I3)"), columns
PRINT*, nullstring
DO k=1,m
DO i=1,columns
WRITE(*,FMT="("//nstring//"I2)") phantom(i,:,k)
END DO
PRINT *, nullstring
END DO
END PROGRAM phantomtest
!---------------------------
SUBROUTINE Phantom_Making(phantom,columns,rows,diags,m)
IMPLICIT NONE
INTEGER, INTENT(IN):: columns, rows, diags, m
REAL, DIMENSION(columns,rows,m), INTENT(INOUT) :: phantom
INTEGER :: i, j, k, l
!Vertical and horizontal rays
DO i=1,rows
phantom(:,i,i) = 1
phantom(i,:,i+(columns)+(diags/2)) = 1
END DO
!Diagonal rays
phantom(1,2,1+columns) = 1
phantom(2,1,1+columns) = 1
phantom(1,columns-1,1+columns+(diags/2)+rows) = 1
phantom(2,columns,1+columns+(diags/2)+rows) = 1
j = columns-1
DO k=2+columns, (diags/2)+columns
phantom(2:columns,:,k) = phantom(1:(columns-1),:,k-1)
IF (((k+1)-columns).LE.columns) phantom(1,k+1-columns,k)=1
END DO
DO l=columns+(diags/2)+rows+2, columns+(diags/2)+rows+1+(diags/2)
j = j-1
phantom(2:columns,:,l) = phantom(1:(columns-1),:,l-1)
IF (j.GT.0) phantom(1,j,l) = 1
END DO
END SUBROUTINE
最佳答案
许多编译器具有的检查可以帮助您进行调试。例如,使用gfortran:
gfortran -g -fcheck=all -Wall segf.f90
segf.f90:5.17:
INTEGER :: i, j, k
1
Warning: Unused variable 'j' declared at (1)
~/f/testy/stackoverflow> ./a.out
At line 50 of file segf.f90
Fortran runtime error: Index '199' of dimension 3 of array 'phantom' outside of expected range (1:198)
其他编译器具有类似的选项。
您的循环在
l
的这些值上运行,而您正在越界访问phantom
数组。确保
l
具有正确的值1:m
,或者确保正确地将数组幻像的尺寸指定为该范围(1:m
)。关于arrays - Fortran 90-带有可扩展3D阵列的 "Segmentation fault - invalid memory reference",我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23130045/