From bb906411e53e310762ec121b625b666afd7d9750 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 v9 2/2] 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 18e657c..84515b8 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;
+	}
 }
 
 /*
@@ -378,6 +381,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),
@@ -610,6 +620,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.18.4

