分段错误 - Fortran中的内存引用无效

问题描述 投票:1回答:1

最近我在我的Fortran代码中收到以下错误

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

Backtrace for this error:
#0  0x2AD9B0F8FE08
#1  0x2AD9B0F8EF90
#2  0x2AD9B12D44AF
#3  0x401A3E in MAIN__ at tstreadin.f90:?

我的代码如下

Program www

 implicit none
 integer ::i,j,rows,cols,row
 real(kind=8) ::x,y,z
 real(kind=8),allocatable::mat(:,:),xrange(:),yrange(:)
 real(kind=8),allocatable::pot_bar(:,:),acc_bar_x(:,:),acc_bar_y(:,:)
 real(kind=8),allocatable::pot_sph(:,:),acc_sph_x(:,:),acc_sph_y(:,:)
 rows=2250000
 cols=8
 row=1500
 allocate(mat(cols,rows))
 allocate(xrange(row),yrange(row),pot_bar(row,row))
 allocate(acc_bar_x(row,row),acc_bar_y(row,row))
 allocate(pot_sph(row,row),acc_sph_x(row,row),acc_sph_y(row,row))
 open(24,file='pot.txt',status='old',form='Formatted', access='SEQUENTIAL')
 do i=1,rows,1
    read(24,*)mat(:,i)
 enddo
 close(24)
 do i=1,rows,row
    xrange(i)=mat(1,i)
 enddo
 do i=1,row,1
    yrange(i)=mat(2,i)
 enddo
 do i=1,row,1
    do j=1,row,1
       pot_bar(j,i)=mat(3,j+(i-1)*1500)
       acc_bar_x(j,i)=mat(4,j+(i-1)*1500)
       acc_bar_y(j,i)=mat(5,j+(i-1)*1500)
       pot_sph(j,i)=mat(6,j+(i-1)*1500)
       acc_sph_x(j,i)=mat(7,j+(i-1)*1500)
       acc_sph_x(j,i)=mat(8,j+(i-1)*1500)
    enddo
 enddo
 print*,xrange
 print*,yrange
end Program www

我想将ASCII配置文件中的数据输入到数组中,因此我编写了测试代码。这是我第一次使用Fortran,我完全无法理解错误出现的原因。

arrays segmentation-fault fortran
1个回答
3
投票

数组xrange只分配了1500个元素。但是在下面

do i=1,rows,row
   xrange(i)=mat(1,i)
enddo

您试图访问一个索引远远超过1500(行>> 1500)的xrange元素。因此无效的内存引用。

© www.soinside.com 2019 - 2024. All rights reserved.