Fortran中派生类型数据的破坏

时间:2016-04-28 05:31:01

标签: fortran gfortran intel-fortran fortran2003

我使用gcc 5.2.0和6.1.0使用以下代码获得分段错误。

module a_module
  implicit none
  type :: a
     character(len=16) :: name = "none"
   contains
     final:: destroy_a
  end type a
contains
  subroutine destroy_a(this)
    type(a), intent(inout) :: this
    print *, "destroying a: ", this%name, loc(this)
  end subroutine destroy_a
end module a_module

module b_module
  use a_module
  implicit none
  type :: b
     character(len=16) :: name = "none"
     type(a) :: object_a
   contains
     final :: destroy_b
  end type b
contains
  subroutine destroy_b (this)
    type(b), intent(inout) :: this
    print *, "destroying b: ", this%name, loc(this)
  end subroutine destroy_b
end module b_module

module c_module
  use b_module
  implicit none
  type :: c
     character(len=16) :: name = "none"
     type(b) :: object_b(2)
   contains
     final :: destroy_c
  end type c
contains
  subroutine destroy_c(this)
    type(c), intent(inout) :: this
    print *, "destroying c: ", this%name, loc(this)
  end subroutine destroy_c
end module c_module

program main
  use c_module
  implicit none
  call f ()
contains
  subroutine f()
    type(c) :: x
    x%name = "object c"
    x%object_b(1)%name = "Object B(1)"
    x%object_b(1)%object_a%name = "object b(1)%a"
    x%object_b(2)%name = "object b(2)"
    x%object_b(2)%object_a%name = "object b(2)%a"
    print *, 'loc of c     ', loc(x)
    print *, 'loc of b(1)  ', loc(x%object_b(1))
    print *, 'loc of b(1)%a', loc(x%object_b(1)%object_a)
    print *, 'loc of b(2)  ', loc(x%object_b(2))
    print *, 'loc of b(2)%a', loc(x%object_b(2)%object_a)
  end subroutine f
end program main

我得到的结果是,

 loc of c           140733747692976
 loc of b(1)        140733747692992
 loc of b(1)%a      140733747693008
 loc of b(2)        140733747693024
 loc of b(2)%a      140733747693040
 destroying c: object c              140733747692976
 destroying a: object b(1)%a         140733747693008
Program received signal SIGSEGV: Segmentation fault - invalid memory
reference.

如果我用英特尔编译代码,它会运行。但结果并不是我的预期。

 loc of c            140737488319232
 loc of b(1)         140737488319248
 loc of b(1)%a       140737488319264
 loc of b(2)         140737488319280
 loc of b(2)%a       140737488319296
 destroying c: object c               140737488319232
 destroying a: object b(1)%a          140737488319264
 destroying a: object b(2)%a          140737488319296

为什么没有调用类型b的析构函数?

所有这些测试都禁用优化。

0 个答案:

没有答案