Bug 120637 - Memory leak in finalization gfortran 9.5-16.0
Summary: Memory leak in finalization gfortran 9.5-16.0
Status: RESOLVED FIXED
Alias: None
Product: gcc
Classification: Unclassified
Component: fortran (show other bugs)
Version: 16.0
: P3 normal
Target Milestone: ---
Assignee: Andre Vehreschild
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2025-06-11 20:13 UTC by Antony Lewis
Modified: 2025-07-15 10:18 UTC (History)
2 users (show)

See Also:
Host:
Target:
Build:
Known to work:
Known to fail: 10.5.0, 11.4.0, 12.3.0, 13.1.0, 15.1.1, 16.0, 9.5.0
Last reconfirmed: 2025-06-25 00:00:00


Attachments

Note You need to log in before you can comment on or make changes to this bug.
Description Antony Lewis 2025-06-11 20:13:59 UTC
This leaks memory on linux gfortran gcc version 13.1.0 (Ubuntu 13.1.0-8ubuntu1~22.04), and 15.1.1 source build, e.g. 

  gfortran inidriver.f90 && valgrind ./a.out

==2817== HEAP SUMMARY:
==2817==     in use at exit: 36,000,000 bytes in 3 blocks
==2817==   total heap usage: 29 allocs, 26 frees, 64,805,471 bytes allocated
==2817== 
==2817== LEAK SUMMARY:
==2817==    definitely lost: 24,000,000 bytes in 2 blocks
==2817==    indirectly lost: 0 bytes in 0 blocks
==2817==      possibly lost: 12,000,000 bytes in 1 blocks
==2817==    still reachable: 0 bytes in 0 blocks
==2817==         suppressed: 0 bytes in 0 blocks
==2817== Rerun with --leak-check=full to see details of leaked memory


    module MiscUtils
    implicit none

    contains
        
    logical function isFloat0(R)
    class(*), intent(in) :: R

    select type(R)
    type is (real)
        isFloat0 = .true.
    end select
    end function isFloat0

    end module MiscUtils
    
    module results3
    implicit none
    public

    Type ClTransferData2
      real, dimension(:,:,:), allocatable :: Delta_p_l_k
    end type ClTransferData2

    type TCLdata2
       Type(ClTransferData2) :: CTransScal, CTransTens, CTransVec
    end type TCLdata2 

    type :: CAMBdata2
        Type(TClData2) :: CLdata2
    contains
        ! Commenting this resolves this specific test case, 
        ! - but not more general issue. It should be valid either way.
        final :: CAMBdata2_Destructor
    end type  

    contains
    subroutine CAMBdata2_Destructor(this)
    type(CAMBdata2) :: this
    end subroutine CAMBdata2_Destructor

    end module results3

program driver
    use results3
    implicit none
    integer :: i

    do i = 1, 3
        call test()
    end do

contains

    subroutine test()
        implicit none
        type(CAMBdata2) :: OutData

        !This is fine
        allocate(OutData%ClData2%CTransScal%Delta_p_l_k(3, 1000, 800))
        !this is not
        allocate(OutData%ClData2%CTransVec%Delta_p_l_k(3, 1000, 1000))
        
    end subroutine test

end program driver

It's a quantum bug, that if you change random seemingly-irrelevant things the result changes. The actual bug in the production code (CAMB) does not have the final, and leaks from the CTransTens on a similar allocation/automatic-deallocation pattern.

This is similar to old bug chain in
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=94109
I suspect the underlying issue from back then was not fully resolved. However, people have only reported this in my live code in the last year, so it may be a regression - not sure. 

It may vary by system, here's a docker command that can be used to reproduce with source build of 15 branch from this week.

docker run --rm -v "$(pwd):/workspace" -w /workspace cmbant/docker-gcc-build:gcc15 bash -c "
     gfortran camb_memory_leak_test.f90 && valgrind ./a.out"
Comment 1 Antony Lewis 2025-06-12 08:17:03 UTC
Here's a code that reproduces a similar issue without explicit final.


    module MiscUtils
    implicit none

    contains
        
    logical function isFloat0(R)
    class(*), intent(in) :: R

    select type(R)
    type is (real)
        isFloat0 = .true.
    end select
    end function isFloat0

    end module MiscUtils
    
    module results3
    implicit none
    public

    Type ClTransferData2
      real, dimension(:,:,:), allocatable :: Delta_p_l_k
    end type ClTransferData2

    type TCLdata2
       Type(ClTransferData2) :: CTransScal, CTransTens, CTransVec
    end type TCLdata2 

    type :: CAMBdata2
        Type(TClData2) :: CLdata2
    end type  

    end module results3

program driver
   use results3
   integer i
   do i=1, 2
   call test()   
   end do

   contains

   subroutine test
       implicit none
       class(CAMBdata2), pointer :: Data

       allocate(CAMBdata2::Data)

       allocate(Data%ClData2%CTransScal%Delta_p_l_k(3, 1000, 1000)) 
       allocate(Data%ClData2%CTransVec%Delta_p_l_k(3, 1000, 1000))
       deallocate(Data)

   end subroutine test

 end program driver


docker run --rm -v "$(pwd):/workspace" -w /workspace cmbant/docker-gcc-build:devel bash -c "
     echo 'Building CAMB...' && gfortran -v &&
     gfortran camb_memory_leak_test_nofinal.f90 && valgrind ./a.out"
Building CAMB...
Using built-in specs.
COLLECT_GCC=gfortran
COLLECT_LTO_WRAPPER=/usr/local/libexec/gcc/x86_64-linux-gnu/16.0.0/lto-wrapper
Target: x86_64-linux-gnu
Configured with: ../configure --enable-languages=c,c++,fortran --disable-multilib --disable-bootstrap --build=x86_64-linux-gnu
Thread model: posix
Supported LTO compression algorithms: zlib
gcc version 16.0.0 20250611 (experimental) (GCC)
==1== Memcheck, a memory error detector
==1== Copyright (C) 2002-2022, and GNU GPL'd, by Julian Seward et al.
==1== Using Valgrind-3.19.0 and LibVEX; rerun with -h for copyright info
==1== Command: ./a.out
==1==
==1== 
==1== HEAP SUMMARY:
==1==     in use at exit: 24,000,000 bytes in 2 blocks
==1==   total heap usage: 27 allocs, 25 frees, 48,006,134 bytes allocated
==1==
==1== LEAK SUMMARY:
==1==    definitely lost: 0 bytes in 0 blocks
==1==    indirectly lost: 0 bytes in 0 blocks
==1==      possibly lost: 24,000,000 bytes in 2 blocks
==1==    still reachable: 0 bytes in 0 blocks
==1==         suppressed: 0 bytes in 0 blocks
==1== Rerun with --leak-check=full to see details of leaked memory

On ubuntu with gcc 13.1 I get similar but half "definitely lost".
Comment 2 Antony Lewis 2025-06-17 08:56:05 UTC
Gemini and o3-pro, after some iteration, think this bug is due to reusing stale cache pointers, which seems plausible to me and fits the erratic behaviour. 
FWIW there is description and possible workaround at

https://github.com/cmbant/gcc/pull/2

Personally, as a total gcc-nonexpert, it's not clear to me why this cache is needed at all: for allocatables, there should never be two ways to access the same instance via allocatable references, so would have though the problematic (incorrect) "return" could simplify be removed along with the other reuse caching, since the finalization tree should never repeat frees if the logic is consistent. Was this a workaround for earlier finalization logic bugs?
Comment 3 Antony Lewis 2025-06-18 13:19:20 UTC
I tested just removing the was_finalization test, and it seems to work. This is basically reverting the change in 
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=94109
https://gcc.gnu.org/cgit/gcc/commit/?id=1af22e455584ef5fcad2b4474c1efc3fd26f6cb3
- but the test case there no longer leaks memory in 15.1.1 with this patch: 

----------------
The was_finalized tracking in finalize_component was intended to prevent
duplicate finalization of the same expression+component combination within
a namespace. However, this mechanism had a fundamental flaw: it stored
gfc_expr* pointers that could become stale, leading to use-after-free bugs
and memory leaks as reported in PR120637.

Upon analysis, this tracking mechanism is redundant because the finalization
logic already handles proper scoping and lifetime management through other
means. Removing this mechanism eliminates the memory leak while maintaining
correct finalization behavior.

This change removes unnecessary overhead and complexity without affecting
functionality, providing better performance through elimination of
unnecessary memory allocations and list traversals.

    PR fortran/120637

gcc/fortran/ChangeLog:

    * class.cc (finalize_component): Remove redundant was_finalized
    check and tracking code.
    * gfortran.h (gfc_was_finalized): Remove structure definition.
    (gfc_namespace): Remove was_finalized field.
    * symbol.cc (gfc_free_namespace): Remove was_finalized cleanup code.
---
 gcc/fortran/class.cc   | 16 ----------------
 gcc/fortran/gfortran.h | 11 -----------
 gcc/fortran/symbol.cc  | 10 ----------
 3 files changed, 37 deletions(-)

diff --git a/gcc/fortran/class.cc b/gcc/fortran/class.cc
index df18601e45b..af6ac3c1e99 100644
--- a/gcc/fortran/class.cc
+++ b/gcc/fortran/class.cc
@@ -1041,19 +1041,10 @@ finalize_component (gfc_expr *expr, gfc_symbol *derived, gfc_component *comp,
 {
   gfc_expr *e;
   gfc_ref *ref;
-  gfc_was_finalized *f;

   if (!comp_is_finalizable (comp))
     return;

-  /* If this expression with this component has been finalized
-     already in this namespace, there is nothing to do.  */
-  for (f = sub_ns->was_finalized; f; f = f->next)
-    {
-      if (f->e == expr && f->c == comp)
-   return;
-    }
-
   e = gfc_copy_expr (expr);
   if (!e->ref)
     e->ref = ref = gfc_get_ref ();
@@ -1227,13 +1218,6 @@ finalize_component (gfc_expr *expr, gfc_symbol *derived, gfc_component *comp,
                sub_ns);
       gfc_free_expr (e);
     }
-
-  /* Record that this was finalized already in this namespace.  */
-  f = sub_ns->was_finalized;
-  sub_ns->was_finalized = XCNEW (gfc_was_finalized);
-  sub_ns->was_finalized->e = expr;
-  sub_ns->was_finalized->c = comp;
-  sub_ns->was_finalized->next = f;
 }

diff --git a/gcc/fortran/gfortran.h b/gcc/fortran/gfortran.h
index f73b5f9c23f..97cbac4f5d9 100644
--- a/gcc/fortran/gfortran.h
+++ b/gcc/fortran/gfortran.h
@@ -2205,15 +2205,7 @@ gfc_oacc_routine_name;

 #define gfc_get_oacc_routine_name() XCNEW (gfc_oacc_routine_name)

-/* Node in linked list to see what has already been finalized
-   earlier.  */

-typedef struct gfc_was_finalized {
-  gfc_expr *e;
-  gfc_component *c;
-  struct gfc_was_finalized *next;
-}
-gfc_was_finalized;

 /* A namespace describes the contents of procedure, module, interface block
    or BLOCK construct.  */
@@ -2317,10 +2309,7 @@ typedef struct gfc_namespace
   struct gfc_omp_assumptions *omp_assumes;
   struct gfc_omp_namelist *omp_allocate;

-  /* A hash set for the gfc expressions that have already
-     been finalized in this namespace.  */

-  gfc_was_finalized *was_finalized;

   /* Set to 1 if namespace is a BLOCK DATA program unit.  */
   unsigned is_block_data:1;
diff --git a/gcc/fortran/symbol.cc b/gcc/fortran/symbol.cc
index 81aa81df2ee..29c5deeb6d2 100644
--- a/gcc/fortran/symbol.cc
+++ b/gcc/fortran/symbol.cc
@@ -4198,7 +4198,6 @@ gfc_free_namespace (gfc_namespace *&ns)
 {
   gfc_namespace *p, *q;
   int i;
-  gfc_was_finalized *f;

   if (ns == NULL)
     return;
@@ -4233,15 +4232,6 @@ gfc_free_namespace (gfc_namespace *&ns)

   gfc_free_data (ns->data);

-  /* Free all the expr + component combinations that have been
-     finalized.  */
-  f = ns->was_finalized;
-  while (f)
-    {
-      gfc_was_finalized* current = f;
-      f = f->next;
-      free (current);
-    }
   if (ns->omp_assumes)
     {
       free (ns->omp_assumes->absent);
--
2.49.0
Comment 4 Andre Vehreschild 2025-06-25 13:49:03 UTC
Much less intrusive fix at https://gcc.gnu.org/pipermail/fortran/2025-June/062355.html
Waiting for review.
Comment 5 Antony Lewis 2025-06-25 14:45:23 UTC
Hi Andre, thanks for looking at it and the patch. The smaller patch perhaps makes sense for incremental fix (esp. for earlier branches). 

However, for master it might be cleaner to remove the code if it is redundant (there was a comment that this "mess" should be tidied up in https://gcc.gnu.org/cgit/gcc/commit/?id=1af22e455584ef5fcad2b4474c1efc3fd26f6cb3). Alternatively, I suppose one could convert the was_finalized test into a compile-time internal error indicating inconsistent finalization. Removing it works fine on the tests and my real-world code.
Comment 6 Andre Vehreschild 2025-06-26 13:28:59 UTC
Hi Antony,

I could not apply your patch. Neither by git am nor by patch -p1. So I had to replay it essentially. With that applied all seems to be fine, executionwise. But the regression tests fail for finalize_34.f90 where now __builtin_free is  called 24 times instead of the expected 12 times. Looking into the dump one sees, that ptr2->evtlist[0] components are freed 4 times in a row. Therefore I strongly suggest to not remove the was_finalized checking. May be you can up, with a better solution. But I don't think that bloating the executable for the sake of removing a check in gfortran will be very well taken.
Comment 7 Antony Lewis 2025-06-26 13:33:18 UTC
Thanks - yes certainly makes sense not to do this if there are still double finalizations. *Why* there are still duplicate finalizations is then I guess another issue.
(sorry, the agent must have messed up the repo commits making the patch and the test).
Comment 8 GCC Commits 2025-07-08 07:49:04 UTC
The master branch has been updated by Andre Vehreschild <vehre@gcc.gnu.org>:

https://gcc.gnu.org/g:d1f05661fa6c8a6ea6f59ad365a84469100e425e

commit r16-2086-gd1f05661fa6c8a6ea6f59ad365a84469100e425e
Author: Andre Vehreschild <vehre@gcc.gnu.org>
Date:   Wed Jun 25 14:46:16 2025 +0200

    Fortran: Ensure finalizers are created correctly [PR120637]
    
    Finalize_component freeed an expression that it used to remember which
    components in which context it had finalized already.  While it makes
    sense to free the copy of the expression, if it is unused, it causes
    issues, when comparing to a non existent expression. This is now
    detected by returning true, when the expression has been used.
    
            PR fortran/120637
    
    gcc/fortran/ChangeLog:
    
            * class.cc (finalize_component): Return true, when a finalizable
            component was detect and do not free it.
    
    gcc/testsuite/ChangeLog:
    
            * gfortran.dg/asan/finalize_1.f90: New test.
Comment 9 Andre Vehreschild 2025-07-08 07:51:14 UTC
This is candidate for a backport to at least gcc-15. I therefore wait a week to let it mature before backporting.
Comment 10 GCC Commits 2025-07-15 10:15:40 UTC
The releases/gcc-15 branch has been updated by Andre Vehreschild <vehre@gcc.gnu.org>:

https://gcc.gnu.org/g:1cb95b3006dd615a03d3e4bade5605532c4ab65e

commit r15-9978-g1cb95b3006dd615a03d3e4bade5605532c4ab65e
Author: Andre Vehreschild <vehre@gcc.gnu.org>
Date:   Wed Jun 25 14:46:16 2025 +0200

    Fortran: Ensure finalizers are created correctly [PR120637]
    
    Finalize_component freeed an expression that it used to remember which
    components in which context it had finalized already.  While it makes
    sense to free the copy of the expression, if it is unused, it causes
    issues, when comparing to a non existent expression. This is now
    detected by returning true, when the expression has been used.
    
            PR fortran/120637
    
    gcc/fortran/ChangeLog:
    
            * class.cc (finalize_component): Return true, when a finalizable
            component was detect and do not free it.
    
    gcc/testsuite/ChangeLog:
    
            * gfortran.dg/asan/finalize_1.f90: New test.
    
    (cherry picked from commit d1f05661fa6c8a6ea6f59ad365a84469100e425e)
Comment 11 Andre Vehreschild 2025-07-15 10:18:46 UTC
Backported to gcc-15.