From 0231208c6ee8e61461a822c1d41b9c4021efed2d Mon Sep 17 00:00:00 2001
From: "houzj.fnst" <houzj.fnst@cn.fujitsu.com>
Date: Mon, 13 Jun 2022 14:42:55 +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 f763a38..4e0c644 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;
+	}
 }
 
 /*
@@ -377,6 +380,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),
@@ -609,6 +619,13 @@ logicalrep_partition_open(LogicalRepRelMapEntry *root,
 		part_entry->partoid = partOid;
 	}
 
+	/* cleanup the invalid attrmap */
+	if (entry->attrmap)
+	{
+		free_attrmap(entry->attrmap);
+		entry->attrmap = NULL;
+	}
+
 	if (!entry->remoterel.remoteid)
 	{
 		int	i;
-- 
2.7.2.windows.1

