Warm tip: This article is reproduced from serverfault.com, please click

Segmentation fault with passing internal function to another procedure

发布于 2020-11-30 00:56:21

I believe the following is a valid Fortran 2008 program and it works fine on genuine macOS, Linux, and Windows operating systems with both Intel and GNU Fortran compilers.

module InternalFuncCaller_mod
    implicit none
    abstract interface 
        function getInternalFunc_proc(input) result(output)
            implicit none
            real, intent(in)    :: input
            real                :: output
        end function getInternalFunc_proc
    end interface
contains
    subroutine callInternalFunc(getInternalFunc, x)
        implicit none
        procedure(getInternalFunc_proc) :: getInternalFunc
        real, intent(in)                :: x
        write(*,*) getInternalFunc(x)
    end subroutine callInternalFunc
end module InternalFuncCaller_mod

module InternalFunc_mod
    implicit none
contains
    subroutine passInternalFunc()
        use InternalFuncCaller_mod, only: callInternalFunc
        implicit none
        call callInternalFunc(getThisInternalFunc, x = 4.)
    contains
        function getThisInternalFunc(x) result(sqrtx)
            implicit none
            real, intent(in)    :: x
            real                :: sqrtx
            sqrtx = sqrt(x)
        end function getThisInternalFunc
    end subroutine passInternalFunc
end module InternalFunc_mod

program testInternalFuncCall
    use InternalFunc_mod
    implicit none
    call passInternalFunc()
    write(*,*) "Done."
end program testInternalFuncCall

However, when compiled with GFortran on a Windows Subsystem for Linux (WSL) (Ubuntu) and run, it gives the following SegFault error message:

Program received signal SIGSEGV: Segmentation fault - invalid memory reference.
Backtrace for this error:
#0  0x7ffb84580d3a
#1  0x7ffb8457fed5
#2  0x7ffb843a620f
#3  0x7fffde946cb0
Segmentation fault (core dumped)

I have traced the issue to the internal function call by the external procedure. But the same code works fine on all other Operating Systems with different Fortran compilers. So, this does not appear to be a bug with GNU GFortran, but more likely an issue with static compilation and execution of code that contains external calls to internal procedures of another procedure, in particular, on WSL OS.

To give more information, I have noticed that the library works fine (even with internal function calls) when it is built as a shared library. However, it fails with the same error message when compiled a static library.

So, it seems like a combination of some GFortran flags can somehow resolve the error (-fPIC -shared). Any help on how to resolve this problem is greatly appreciated.

Questioner
King
Viewed
0
Rob 2020-11-30 17:25:21

As the person with the problem in Segmentation fault when passing internal function as argument I've found moving to WSL version 2 fixes the issue for me.