Hello,

Harald found a testcase with memory still leaking despite my previous patch for PR108923. That patch was fixing a leak caused by absence of memory release, the attached patch fixes a leak caused by pointer overwrite.

I haven't investigated why sort_actual is called several times( which causes the memory leak) nor tried to avoid that. Theoretically, one could assert that the previous associated_dummy value is the same as the one to be written (it should be the same at each sort_actual invocation), but I have preferred to silently overwrite, and fix just the memory problem.

Manually tested on Harald's testcase (predcom-1.f) and ran the full fortran testsuite on x86_64-pc-linux-gnu.

OK for master and 12 and 11?
From 9b88208ec4130712d33d5c7ed74fc17466624a0c Mon Sep 17 00:00:00 2001
From: Mikael Morin <mik...@gcc.gnu.org>
Date: Sat, 25 Feb 2023 16:27:24 +0100
Subject: [PATCH] fortran: Reuse associated_dummy memory if previously
 allocated [PR108923]

This avoids making the associted_dummy field point to a new memory chunk
if it's already pointing somewhere, in which case doing so would leak the
previously allocated chunk.

gcc/fortran/ChangeLog:

	* intrinsic.cc (get_intrinsic_dummy_arg,
	set_intrinsic_dummy_arg): Rename the former to the latter.
	Remove the return value, add a reference to the lhs as argument,
	and do the pointer assignment inside the function.  Don't do
	it if the pointer is already non-NULL.
	(sort_actual): Update caller.
---
 gcc/fortran/intrinsic.cc | 11 +++++------
 1 file changed, 5 insertions(+), 6 deletions(-)

diff --git a/gcc/fortran/intrinsic.cc b/gcc/fortran/intrinsic.cc
index 17ee999c3b9..e69e541efe0 100644
--- a/gcc/fortran/intrinsic.cc
+++ b/gcc/fortran/intrinsic.cc
@@ -4259,15 +4259,14 @@ remove_nullargs (gfc_actual_arglist **ap)
 }
 
 
-static gfc_dummy_arg *
-get_intrinsic_dummy_arg (gfc_intrinsic_arg *intrinsic)
+static void
+set_intrinsic_dummy_arg (gfc_dummy_arg *&dummy_arg, gfc_intrinsic_arg *intrinsic)
 {
-  gfc_dummy_arg * const dummy_arg = gfc_get_dummy_arg ();
+  if (dummy_arg == NULL)
+    dummy_arg = gfc_get_dummy_arg ();
 
   dummy_arg->intrinsicness = GFC_INTRINSIC_DUMMY_ARG;
   dummy_arg->u.intrinsic = intrinsic;
-
-  return dummy_arg;
 }
 
 
@@ -4430,7 +4429,7 @@ do_sort:
       if (a == NULL)
 	a = gfc_get_actual_arglist ();
 
-      a->associated_dummy = get_intrinsic_dummy_arg (f);
+      set_intrinsic_dummy_arg (a->associated_dummy, f);
 
       if (actual == NULL)
 	*ap = a;
-- 
2.39.1

Reply via email to