Search code examples
fortrangfortranallocation

Assignment to unallocated variable


A line in my code assigns an array to an unallocated array. I thought it was a bug but to my surprise it works just fine.

program test
implicit none
    real, allocatable :: x(:,:)
    real :: y(2,2)

    y = 1.
    x = y

    print*, x
end program test

How does this work in terms of memory? The = operator here just allocates and assigns at the same time? Why is this possible and why is the compiler not complaining? I am using gfortran 5.4.0.


Solution

  • Since Fortran 2003, allocatable arrays will be automatically allocated (or re-allocated if the shape has changed) at run time. See for instance the Fortran 2003 features of the NAG compiler https://www.nag.com/nagware/np/r61_doc/nag_f2003.pdf or look for "realloc" in the documentation of gfortran https://gcc.gnu.org/onlinedocs/gfortran/Error-and-Warning-Options.html#Error-and-Warning-Options