Matthias 009
Matthias 009

Reputation: 1712

Why is my array not allocated any more inside subroutine?

I have a Fortran type which has an entry which is a type again. This type has an allocatable integer array:

type inner
    integer, allocatable :: dyn_arr(:)
    integer another_var
end type
type outer
    type(inner) entry
    type(inner) another_entry
end type

I allocate the array and then call a subroutine. Inside the subroutine I want to access the array.

type(outer) main_struct

allocate(main_struct%entry%dyn_arr(100))
call routi(main_struct)

My code segfaults. When I run with debugger, before the call everything seems fine, when I enter the subroutine routi, the debugger says dyn_arr is not allocated. How can that be?

Upvotes: 2

Views: 477

Answers (2)

amicitas
amicitas

Reputation: 13671

I created a short program to test this and did not have any problems. Could you post a short program that shows this failure?

Here is my code that worked fine when compiled using gfortran 4.5:

  MODULE temp_module
    TYPE inner
       INTEGER, ALLOCATABLE :: dyn_arr(:)
       INTEGER another_var
    END TYPE inner
    TYPE outer
       TYPE(inner) entry
       TYPE(inner) another_entry
    END TYPE outer
  CONTAINS

    SUBROUTINE test (input)
      TYPE(outer), INTENT(in) :: input
      WRITE(*,*) input%entry%dyn_arr
    END SUBROUTINE test

  END MODULE temp_module

  PROGRAM XC_VMEC_SIGHTLINE
    USE temp_module
    TYPE(outer) main_struct

    ALLOCATE(main_struct%entry%dyn_arr(10))
    CALL test(main_struct)
  END PROGRAM XC_VMEC_SIGHTLINE

Upvotes: 2

Stefano Borini
Stefano Borini

Reputation: 143905

I guess that in routi() you have an intent(out), havent't you ?

From here

An allocated ultimate allocatable component of an actual argument that is associated with an INTENT(OUT) dummy argument is deallocated on procedure entry so that the corresponding component of the dummy argument has an allocation status of not currently allocated.

This ensures that any pointers that point to the previous contents of the allocatable component of the variable become undefined.

Never use intent(out). It's evil.

Upvotes: -6

Related Questions