From 6c23fc9c52531cbce97db1741792f4b6a4c04c8d Mon Sep 17 00:00:00 2001
From: Nitin Jadhav <nitinjadhav@microsoft.com>
Date: Fri, 5 Jul 2024 11:51:36 +0000
Subject: [PATCH] Address the -Wuse-after-free warning in
 ATExecAttachPartition()

Address the warning in the ATExecAttachPartition() function, where
the partBoundConstraint variable was used after the list_concat()
function. This could result in the partBoundConstraint variable
being accessed after its memory has been released. The resolution
is to use the return value of the list_concat() function, rather
than using the list1 argument of list_concat().
---
 src/backend/commands/tablecmds.c | 12 +++++++++---
 1 file changed, 9 insertions(+), 3 deletions(-)

diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c
index 8fcb188323..ba3c3c0f29 100644
--- a/src/backend/commands/tablecmds.c
+++ b/src/backend/commands/tablecmds.c
@@ -18362,7 +18362,6 @@ ATExecAttachPartition(List **wqueue, Relation rel, PartitionCmd *cmd,
 	Relation	attachrel,
 				catalog;
 	List	   *attachrel_children;
-	List	   *partConstraint;
 	SysScanDesc scan;
 	ScanKeyData skey;
 	AttrNumber	attno;
@@ -18561,12 +18560,19 @@ ATExecAttachPartition(List **wqueue, Relation rel, PartitionCmd *cmd,
 	 * constraint as well.
 	 */
 	partBoundConstraint = get_qual_from_partbound(rel, cmd->bound);
-	partConstraint = list_concat(partBoundConstraint,
+	partBoundConstraint = list_concat(partBoundConstraint,
 								 RelationGetPartitionQual(rel));
 
 	/* Skip validation if there are no constraints to validate. */
-	if (partConstraint)
+	if (partBoundConstraint)
 	{
+		/*
+		 * Preserve the modifications applied to partBoundConstraint by storing
+		 * them in a new variable. This will be utilized later to reconstruct
+		 * the constraint of the default partition.
+		 */
+		List	*partConstraint = partBoundConstraint;
+
 		/*
 		 * Run the partition quals through const-simplification similar to
 		 * check constraints.  We skip canonicalize_qual, though, because
-- 
2.43.0

