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

Crash when deallocating function return type

Andersen__Christian
641 Views

I have a crash when returning a pointer to an allocated type in a function. When the pointer is deallocated before returning, the destructor of the type is called with a wrong argument. I don't know if this has been fixed in a newer compiler. I am on   

Intel(R) Visual Fortran Intel(R) 64 Compiler for applications  running on Intel(R) 64, Version 17.0.5.267 Build 20170817

See below code. I'm sorry if I have done something that is not valid fortran or made a mistake..

program main
  use crash_module
  implicit none
  
  type(struct), pointer :: x
    
  ! Using:
  ! Intel(R) Visual Fortran Intel(R) 64 Compiler for applications
  ! running on Intel(R) 64, Version 17.0.5.267 Build 20170817
  x => crash()
  
end program
module crash_module
  
implicit none
private

public :: struct, crash

type :: struct
  private
  integer :: filler1 = 123
  integer :: filler2 = 123
  integer :: filler3 = 123
  integer :: filler4 = 123
  integer, pointer :: p => null()
contains 
  private
  final :: destructor
end type

contains

impure elemental subroutine destructor(this)
  type(struct), intent(inout) :: this
  ! See that filler1, 2, 3, 4 have wrong values (should be 123).
  ! Crash because p is not null
  if (associated(this%p)) deallocate(this%p)
end subroutine

function crash() result(attribute)
  type(struct), pointer :: attribute
  allocate(attribute)
  ! destructor is called with a bogus argument.
  deallocate(attribute)
end function

end module

 

0 Kudos
2 Replies
Arjen_Markus
Honored Contributor I
641 Views

You are destructing the result of the function before the function can return. If this would succeed, would the result not be a dangling pointer? I can imagine this to work if you nullify the pointer after deallocation.

0 Kudos
Andersen__Christian
641 Views

Yes, nullifying it doesn't change that it crashes.

0 Kudos
Reply