From 71ac8f2a7cb04e32dc37b3f7245e819c0b0335c9 Mon Sep 17 00:00:00 2001
From: "Hou Zhijie" <houzj.fnst@cn.fujitsu.com>
Date: Sat, 11 Jun 2022 16:37:51 +0800
Subject: [PATCH] fix memory leak about attrmap

Use free_attrmap instead of pfree to release AttrMap structure.
Check the attrmap again when opening the relation and clean up the
invalid AttrMap before rebuilding it.

---
 src/backend/replication/logical/relation.c | 19 ++++++++++++++++++-
 1 file changed, 18 insertions(+), 1 deletion(-)

diff --git a/src/backend/replication/logical/relation.c b/src/backend/replication/logical/relation.c
index 324b526..e6543ab 100644
--- a/src/backend/replication/logical/relation.c
+++ b/src/backend/replication/logical/relation.c
@@ -144,7 +144,10 @@ logicalrep_relmap_free_entry(LogicalRepRelMapEntry *entry)
 	bms_free(remoterel->attkeys);
 
 	if (entry->attrmap)
-		pfree(entry->attrmap);
+	{
+		free_attrmap(entry->attrmap);
+		entry->attrmap = NULL;
+	}
 }
 
 /*
@@ -389,6 +392,13 @@ logicalrep_rel_open(LogicalRepRelId remoteid, LOCKMODE lockmode)
 		int			i;
 		Bitmapset  *missingatts;
 
+		/* cleanup the invalid attrmap */
+		if (entry->attrmap)
+		{
+			free_attrmap(entry->attrmap);
+			entry->attrmap = NULL;
+		}
+
 		/* Try to find and lock the relation by name. */
 		relid = RangeVarGetRelid(makeRangeVar(remoterel->nspname,
 											  remoterel->relname, -1),
@@ -621,6 +631,13 @@ logicalrep_partition_open(LogicalRepRelMapEntry *root,
 		part_entry->partoid = partOid;
 	}
 
+	/* cleanup the invalid attrmap */
+	if (entry->attrmap)
+	{
+		free_attrmap(entry->attrmap);
+		entry->attrmap = NULL;
+	}
+
 	/* Remote relation is copied as-is from the root entry. */
 	if (!entry->remoterel.remoteid)
 		logicalrep_update_remoterel(entry, remoterel);
-- 
2.7.2.windows.1

