延迟长度字符作为实际arg

时间:2014-06-20 06:27:28

标签: fortran character

program as_actual_arg
    implicit none
    interface 
      subroutine as_actual1(defchar)
        implicit none
        character(len=*), intent(out) :: defchar
      end subroutine

      subroutine as_actual2(defchar)
        implicit none
        character(len=:), allocatable, intent(out) :: defchar
      end subroutine
    end interface

    character(len=:), allocatable :: defchar

    call as_actual1(defchar)
    print *, defchar
    call as_actual2(defchar)
    print *, defchar
end program


subroutine as_actual1(defchar)
    implicit none
    character(len=*), intent(out) :: defchar
    print *, 'length : ', len(defchar)

    defchar = "1234567890"
end subroutine

subroutine as_actual2(defchar)
    implicit none
    character(len=:), allocatable, intent(out) :: defchar

    defchar = "2345678901"
end subroutine

+++++++++++++++++++++++++++++++++++++++++++++++ +++++++++++++++++++++++++++++ gfortran 4.8.2 on ubuntu 14.04

$gfortran as_actual_arg.f90 -std=f2003
$./a.out
length :        32767

Program received signal SIGSEGV: Segmentation fault - invalid memory reference.

Backtrace for this error:
#0  0x7F83873497D7
#1  0x7F8387349DDE
#2  0x7F8386FA0FEF
#3  0x400B5C in as_actual1_
#4  0x400BB0 in MAIN__ at as_actual_arg.f90:?

seg fault

ifort 14

$ifort as_actual_arg.f90 -stand=f03
$./a.out
 length :            0

 2345678901

并在正常情况下终止 ++++++++++++++++++++++++++++++++++++++++++++++++++ ++++++++++++++++++++++

这是什么标准?

2 个答案:

答案 0 :(得分:3)

您的程序不一致 - 当伪参数不可分配时,您使用未分配的实际参数调用as_actual1。具有适当调试选项的ifort将在运行时识别它。

在调用as_actual1之前,在主程序中分配defchar变量(也将指定变量的长度)。

答案 1 :(得分:1)

正如IanH所建议的,如果您使用编译器提供的工具,您会发现开发程序更容易。如果使用调试编译器选项,gfortran和ifort都会发现问题:

gfortran:

At line 29 of file as_actual_arg.f90
Fortran runtime error: Allocatable actual argument 'defchar' is not allocated

使用编译器选项:

-O2  -fimplicit-none  -Wall  -Wline-truncation  -Wcharacter-truncation  -Wsurprising  -Waliasing  -Wimplicit-interface  -Wunused-parameter  -fcheck=all  -std=f2008  -pedantic  -fbacktrace

ifort(旧版):

forrtl: severe (408): fort: (7): Attempt to use pointer DEFCHAR when it is not associated with a target

使用编译器选项:

-O2  -stand f03    -assume realloc_lhs  -check all  -traceback  -warn all  -fstack-protector  -assume protect_parens  -implicitnone

使用您的程序版本:

module MyMod

contains

subroutine as_actual1(defchar)
    implicit none
    character(len=*), intent(out) :: defchar
    print *, 'length : ', len(defchar)

    defchar = "1234567890"
end subroutine

subroutine as_actual2(defchar)
    implicit none
    character(len=:), allocatable, intent(out) :: defchar

    defchar = "2345678901"
end subroutine

end module MyMod

program as_actual_arg
    use MyMod
    implicit none


    character(len=:), allocatable :: defchar

    call as_actual1(defchar)
    print *, defchar
    call as_actual2(defchar)
    print *, defchar
end program

节省了编写接口块的工作量。模块具有自动化......简单可靠。