Error Fortran 90: Program received signal SIGSEGV

1

This is my program:

program ejercicio8
implicit none
real(kind=8) :: i, k, pi
integer, allocatable :: n
integer :: j
real, dimension(:),allocatable :: array
pi= 4*atan(1.0_8)

!----------------------------------------------------------------   


print*, "enter dimension n"
    read(*,*) n
    allocate(array(n))
    j=0
do while (j <= n)
    array(j) = pi+(j/n)*pi
    write(*,*) array(j)
    j = j + 1
enddo
end program ejercicio8

The objective is to generate a vector of dimension variable n and assign each component a value of a range (pi, 2pi) , dividing that interval into n parts. For example: if n = 4, the vector would result (pi, 5/4 pi, 3/2 pi, 2pi)

My code compiles but when I start the program I get this:

  

Program received signal SIGSEGV: Segmentation fault - invalid memory reference

    
asked by Santiagot Gimenez 26.01.2018 в 20:38
source

2 answers

1

The problem was the generation of one more dimension as Alvaro says, and besides the line integer, allocatable :: n it was not necessary to reserve memory for the n.

    
answered by 02.02.2018 в 13:37
0

Memory reserves for an array of size n in this line:

 allocate(array(n))

But then in the loop you access n + 1 memory locations because you start at 0 and continue as long as j is less than or equal to n :

    j=0
do while (j <= n)
    array(j) = pi+(j/n)*pi
    write(*,*) array(j)
    j = j + 1
enddo

You have reserved memory for 4 items, but you try to access 5. For example, if n is 4. You will try to access the position in indexes 0, 1, 2, 3 and 4. When accessing a Memory position that you have not reserved will receive a segmentation error, which is what you see.

Either you have to write in memory as long as j is less (without the equal) to n , or you have to make j start at 1. I have no experience with Fortran, but if I'm not wrong, is a language whose first index is 1, therefore you should opt for the second option.

    
answered by 27.01.2018 в 04:20