Fortran释放派生类型coarray组件时触发段错误,是否为编译器bug?
派生类型coarray组件赋值后释放触发段错误的问题分析
你遇到的情况确实是Intel Fortran Compiler 19.0.3版本的编译器bug。
问题原因
Fortran标准要求,包含可分配coarray的派生类型执行默认赋值时,编译器需要正确复制coarray的所有关联元数据(包括跨镜像的管理信息)。但ifort 19.0.3的默认赋值逻辑存在缺陷:虽然表面上复制了coarray的维度信息(所以size(nmt2%coarr)能正常返回),但底层的coarray内部管理结构没有被正确初始化或复制,导致后续执行deallocate(nmt2%coarr)时访问非法内存,触发段错误。
解决方案
- 升级编译器:Intel在后续版本(比如2021及以后的oneAPI HPC Toolkit中的ifx/ifort)已经修复了这个coarray赋值的问题,升级到最新版本即可解决。
- 手动定义赋值运算符:如果暂时无法升级编译器,可以为派生类型显式定义赋值操作,手动处理coarray的分配与复制,绕过默认赋值的bug:
program mytest implicit none type notmytype real, allocatable :: coarr(:)[:] contains generic :: assignment(=) => assign_notmytype procedure :: assign_notmytype end type notmytype type(notmytype) :: nmt, nmt2 allocate(nmt%coarr(10)[*]) nmt2 = nmt deallocate(nmt2%coarr) contains subroutine assign_notmytype(this, rhs) class(notmytype), intent(out) :: this type(notmytype), intent(in) :: rhs ! 先释放目标对象已分配的coarray if (allocated(this%coarr)) deallocate(this%coarr) ! 复制源对象的coarray if (allocated(rhs%coarr)) then allocate(this%coarr(size(rhs%coarr))[*]) this%coarr = rhs%coarr end if end subroutine assign_notmytype end program mytest
内容的提问来源于stack exchange,提问作者water
相关产品推荐
相关产品推荐

