From 141601d9025806e5d1fc2a739fe391335a817534 Mon Sep 17 00:00:00 2001
From: Vignesh C <vignesh21@gmail.com>
Date: Wed, 2 Jul 2025 10:26:02 +0530
Subject: [PATCH v1] Fix referencing invalid pointer in logical decoding after
 error

When an error occurs while processing changes with conflicting
column lists in different publications, the entry->columns memory
which is allocated in entry private context is freed. However, the
RelationSyncCache still holds a pointer to this memory, leading to
a crash on subsequent access.

To fix this, ensure FreeDecodingContext is called in the error path,
properly clearing the stale cache and preventing use-after-free.
---
 src/backend/replication/logical/logicalfuncs.c | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)

diff --git a/src/backend/replication/logical/logicalfuncs.c b/src/backend/replication/logical/logicalfuncs.c
index ca53caac2f2..0d674f3c2bd 100644
--- a/src/backend/replication/logical/logicalfuncs.c
+++ b/src/backend/replication/logical/logicalfuncs.c
@@ -106,7 +106,7 @@ pg_logical_slot_get_changes_guts(FunctionCallInfo fcinfo, bool confirm, bool bin
 	MemoryContext oldcontext;
 	XLogRecPtr	end_of_wal;
 	XLogRecPtr	wait_for_wal_lsn;
-	LogicalDecodingContext *ctx;
+	LogicalDecodingContext *ctx = NULL;
 	ResourceOwner old_resowner = CurrentResourceOwner;
 	ArrayType  *arr;
 	Size		ndim;
@@ -314,6 +314,10 @@ pg_logical_slot_get_changes_guts(FunctionCallInfo fcinfo, bool confirm, bool bin
 	}
 	PG_CATCH();
 	{
+		/* free context, call shutdown callback */
+		if (ctx)
+			FreeDecodingContext(ctx);
+
 		/* clear all timetravel entries */
 		InvalidateSystemCaches();
 
-- 
2.43.0

