[fortran] segmentation fault

I am having problems with a bunch of lines returning a segmentation fault. Usually I tend to debug those problems pretty easily, but this time it appears I cannot solve the bug.

 do i = 1,newSize
       call random_number(r1)
       jdo: do j = 1,maxK
          if(r1 <= cs(j)) then
             newSample(i)%k = j; 
             exit jdo
          end if
       end do jdo
    end do

the array of the structure “newSample” has enough elements and the structure itself contains the field “k”.
The real array “cs” is large enough.

the code works as expected producing the expected results using other compilers (i’ve tested several versions of the gnu compiler and a couple of the intel one).

I do compile only using the “-g -O0” flags.

Any help will be appreciated, thanks.

I am afraid that you will have to supply more details to enable the code to seg-fault. Here, for instance, is a complete program that contains a superset of your code and runs without a hitch with PGI 15.3.

program ericman
implicit none
integer, parameter :: newSize=10, maxK=5
!
type nstruc
   integer :: k
end type
!
type(nstruc) :: newSample(newSize)
!
integer :: i,j
real :: r1, cs(maxK)
do i=1,maxK
   r1=(i-1.0)/(maxK-1)
   cs(i) = r1*(1.0+r1)*0.5
end do
write(*,*)cs

do i = 1,newSize
       call random_number(r1)
       write(*,*)'r1 = ',r1
       jdo: do j = 1,maxK
          if(r1 <= cs(j)) then
             newSample(i)%k = j;
             exit jdo
          end if
       end do jdo
end do
write(*,'(2i5)')(i,newsample(i)%k,i=1,9,2)
end program

Note that since your program uses randomly generated numbers, its running behavior and output results are in general not reproducible.

Hi EricMan,

When I see this type of behavior, i.e. it works with -O0 on one platform or compiler but not another and doesn’t reproduce in a simple case, my first instinct is to look for un-initialized memory. For this I highly recommend using Valgrind (http://valgrind.org/). Of course the issue could be something else, but I’d start there.

  • Mat

you’re both right.
the crash apparently depends on the fact that “newSample” is an assumed dimension array of structures declared as result in a function.

I’ve declared it as dimension(:),allocatable and added an
if(.not.allocated(newSample))allocate(newSample(newSize)
and the code is working back.

(of course, now I don’t know if the memory is leaking but this is a secondary problem at the moment)