From d1e8d4c7fe49cdf754e5ebad75fa05e9ef17da78 Mon Sep 17 00:00:00 2001
From: "houzj.fnst" <houzj.fnst@cn.fujitsu.com>
Date: Wed, 22 Jun 2022 09:48:20 +0800
Subject: [PATCH] Fix memory leak about attrmap

When rebuilding the relcache mapping on subscriber, we didn't release the
no longer useful attribute mapping's memory which would result in memory
leak. Fix it by releasing the no longer useful mapping's memory when
rebuilding.

Since attribute mappings was refactored on PG13~HEAD, we should use
free_attrmap instead of pfree to release its memory on these branches. Fix
one place where we still use pfree to release the mapping memory.

Author: Hou Zhijie
Reviewed-by: Amit Langote, Amit Kapila, Shi yu
Backpatch-through: 10, where it was introduced
Discussion: https://postgr.es/m/OSZPR01MB6310F46CD425A967E4AEF736FDA49@OSZPR01MB6310.jpnprd01.prod.outlook.com
---
 src/backend/replication/logical/relation.c | 7 +++++++
 1 file changed, 7 insertions(+)

diff --git a/src/backend/replication/logical/relation.c b/src/backend/replication/logical/relation.c
index bc87105..aa41b79 100644
--- a/src/backend/replication/logical/relation.c
+++ b/src/backend/replication/logical/relation.c
@@ -260,6 +260,13 @@ logicalrep_rel_open(LogicalRepRelId remoteid, LOCKMODE lockmode)
 		MemoryContext oldctx;
 		int			i;
 
+		/* Release the no-longer-useful attrmap, if any. */
+		if (entry->attrmap)
+		{
+			pfree(entry->attrmap);
+			entry->attrmap = NULL;
+		}
+
 		/* Try to find and lock the relation by name. */
 		relid = RangeVarGetRelid(makeRangeVar(remoterel->nspname,
 											  remoterel->relname, -1),
-- 
2.7.2.windows.1

