Fortran 90 - "分段错误 - 内存参考无效"具有可扩展的3D阵列

时间:2014-04-17 09:59:06

标签: arrays segmentation-fault fortran fortran90 gfortran

我用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

1 个答案:

答案 0 :(得分:8)

许多编译器的检查可以帮助您进行调试。例如,使用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,或者将数组幻像的尺寸正确指定为此范围({{1}})。