https://gcc.gnu.org/bugzilla/show_bug.cgi?id=125535

            Bug ID: 125535
           Summary: Wrong-code for implied-do with allocatable-component
                    derived type and transformational intrinsic
           Product: gcc
           Version: 16.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: fortran
          Assignee: unassigned at gcc dot gnu.org
          Reporter: jvdelisle at gcc dot gnu.org
  Target Milestone: ---

When a nested implied-do array constructor calls a  transformational intrinsic
(e.g. RESHAPE) and the element type is a derived type with allocatable
components, gfortran produces wrong runtime values or crashes with a
heap-use-after-free.

The argument temporaries are freed before the result's allocatable components
are deep-copied.  Since RESHAPE does a shallow byte-copy, the result's
component pointers alias those of the temporaries, so freeing first yields
use-after-free.

  module m
    implicit none
    type :: t
      real, allocatable :: v(:)
    end type
  contains
    pure function make (x) result (r)
      real, intent(in) :: x(:)
      type(t) :: r
      r%v = x
    end function
  end module

  program test
    use m
    implicit none
    integer, parameter :: n = 3, k = 2
    type(t), allocatable :: a(:,:)
    real :: h(k, n)
    integer :: i, j

    h(1,:) = [10., 20., 30.]
    h(2,:) = [11., 21., 31.]

    a = reshape ([([(make (h(:,i)), j=1,1)], i=1,n)], [1,n])

    if (any (a(1,1)%v /= h(:,1))) stop 1
    if (any (a(1,2)%v /= h(:,2))) stop 2
    if (any (a(1,3)%v /= h(:,3))) stop 3
  end program

  $ gfortran implied_do_alloc_comp_1.f90 && ./a.out

  The program stops at STOP 1 or crashes with a
  heap-use-after-free.  It should run and exit cleanly.

This one could be related to 90519 and 96910, not sure

Reply via email to