1

Lately I received the following error in my Fortran code

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:?

and my code as follows

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

I want to input data from the ASCII profile to the arrays,so I write the code for test. This is my first time using Fortran, and I completely can't understand why the error appeared.

Jackunicorn
  • 11
  • 1
  • 2
  • Welcome, please take the [tour]. Enable debugging checks in your compiůer to identify bugs easily. Learn flags `-g -fbacktrace -Wall -fcheck=all` in gfortran manual. They are VERY useful. When showing an error message, the `-g` flag should always be used. Note that `kind=8` is an ugly bad practice and makes the code not portable. `8` does NOT mean double precision in all compilers. See https://stackoverflow.com/questions/838310/fortran-90-kind-parameter – Vladimir F Героям слава Dec 18 '17 at 20:10

1 Answers1

4

The array xrange only has 1500 elements allocated. However in the following

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

you are attempting to access an element of xrange with an index far greater than 1500 (rows >> 1500). Hence the invalid memory reference.