[PATCH] Fix memory leak found as a followup to the 125535 commit

Jerry D jvdelisle2@gmail.com
Sun Jun 14 00:15:49 GMT 2026


See attached patch. This fixes a memory leak we found after committing the 
original fix. We should get this in there before I forget.

Regression tested on x86_64.

OK for mainline and later backport when things have settled a bit?

Regards,

Jerry

PS I need to fix a PR reference in the asan/implied_do_alloc_comp_leak_1.f90 
before the push.

---

fortran: [PR125535] Plug remaining leak in implied-do array
  constructor with allocatable components

Follow-up to the PR fortran/125535 wrong-code fix (commit 1b8421e9d5b,
already pushed): that fix corrected the *values* produced by an
implied-do array constructor of derived-type function results with
allocatable components, but left a separate memory leak in the same
code path.

An array constructor whose implied-do produces function results of a
derived type with allocatable components moves each result into the
constructor temporary, so the temporary owns those components.  The
per-element finalization in gfc_trans_array_ctor_element only freed
the single slot referenced by the final loop offset, leaking the
allocatable components of every other element the loop produced.

A whole-array sweep is the only way to free every slot written by an
implied-do, but it may be used only when every element is an owned
function result: a variable element is shallow-copied into the
temporary and its components are aliased rather than owned, so freeing
them would double free.  Add gfc_constructor_is_owned_alloc_comp to
detect the all-owned case and, when it holds, suppress the per-element
finalization and emit a single gfc_deallocate_alloc_comp_no_caf over
the whole temporary.

Assisted by: Claude Opus 4.8

	PR fortran/125535

gcc/fortran/ChangeLog:

	* trans-array.cc (gfc_constructor_is_owned_alloc_comp): New function.
	(gfc_trans_array_constructor_value): Add OWNED_SWEEP parameter and,
	when set, suppress the per-element finalization.  Pass it through the
	recursive call.
	(trans_array_constructor): Compute OWNED_SWEEP and, when set,
	deallocate the allocatable components of the whole temporary in one
	sweep.

gcc/testsuite/ChangeLog:

	* gfortran.dg/asan/implied_do_alloc_comp_leak_1.f90: New test.
---
-------------- next part --------------
A non-text attachment was scrubbed...
Name: PR125535a-implied-do-alloc-comp-leak.patch
Type: text/x-patch
Size: 8572 bytes
Desc: not available
URL: <https://gcc.gnu.org/pipermail/fortran/attachments/20260613/c51ff95e/attachment.bin>


More information about the Fortran mailing list