Intel® Fortran Compiler
Build applications that can scale for the future with optimized code designed for Intel® Xeon® and compatible processors.
29275 Discussions

Function returning POINTER as actual argument?

Thomas_F_1
Beginner
391 Views

I am having problems with ifort (15.0.0.077) when a function returning a pointer is an actual argument to a function with a pointer dummy argument. If I use a temporary pointer variable, the function call works as expected. But if I place the function call directly as the actual argument, I get random crashes and/or garbage when I run the compiled code. I've created a simple example that demonstrates the problem. I don't see anything in Metcalf, Reid, and Cohen that suggests this isn't allowed. Certainly the compiler doesn't complain about it.

module m

    type int
        integer :: i = 0
    end type
    
    class(int), pointer :: mptr => NULL()
    
contains
    subroutine SetPtr(ptr)
        class(int), pointer, intent(in) :: ptr
        mptr => ptr
    end subroutine
    
    function GetPtr()
        class(int), pointer :: GetPtr
        GetPtr => mptr
    end function
    
    subroutine PrintPtr(ptr)
        class(int), pointer, intent(in) :: ptr
        if (associated(ptr)) then
            print "('Val: ',i0)", ptr%i
        else
            print "(a)", "Null pointer"
        endif
    end subroutine

end module m

!===============================================================================

program test
call run
end program

subroutine run
use m
implicit none

    class(int), pointer :: value
    class(int), pointer :: ptr
    
    nullify(ptr)
    allocate(value)
    value%i = 23
    call SetPtr(value)
    
    call PrintPtr(value)     ! Prints "Val: 23"
    call PrintPtr(ptr)       ! Prints "Null pointer"
    
    ptr => GetPtr()
    call PrintPtr(ptr)       ! Prints "Val: 23"
    call PrintPtr(GetPtr())  ! Prints "Val: <random garbage>"
    
    deallocate(value)
    return
    
end subroutine

 

0 Kudos
1 Reply
Steven_L_Intel1
Employee
391 Views

Thanks, we'll take a look.

0 Kudos
Reply