Why am I getting a segmentation fault here (M1 Mac)?

The segfault could be due to the internal function bla(). Converting it to a regular procedure may resolve the segfault.

I do not know much about M1, but the segfault can be reproduced in Linux by marking the output binary as not requiring an executable stack (internal functions require an executable stack with gfortran).

gfortran-10 -cpp -DEXECSTACK_ENABLED segfault.f90; execstack -c ./a.out; ./a.out
Program received signal SIGSEGV: Segmentation fault - invalid memory reference.

Try this alternative code to see if this is indeed the source of error,

module mylib

    implicit none
    integer, parameter :: RK = kind(1.d0)

#if !EXECSTACK_ENABLED
    real(RK) :: a
#endif

    abstract interface
        subroutine fcn_p
        end subroutine
    end interface

contains

#if EXECSTACK_ENABLED
    subroutine tester()
        real(RK) :: a
        a = 20.d0
        call dumb(bla)
    contains
        subroutine bla()
          print*,a
        end subroutine
    end subroutine
#else
    subroutine tester()
        a = 20.d0
        call dumb(bla)
    end subroutine
    subroutine bla()
      print*,a
    end subroutine
#endif

    subroutine dumb(fcn)
        procedure(fcn_p) :: fcn
        call fcn()
    end subroutine

end module

program main
    use mylib
    implicit none
    call tester()
end program
gfortran-10 -cpp segfault.f90; ./a.out

   20.000000000000000 
3 Likes