From f7332e88b901fbca98d5c3df83b2358548ad07e8 Mon Sep 17 00:00:00 2001
From: Tom Lane <tgl@sss.pgh.pa.us>
Date: Tue, 28 Sep 2004 00:49:04 +0000
Subject: [PATCH] Remove duplicate PQclear(res) operations leading to double
 free() and subsequent core dump.  It looks like at one time
 DBLINK_RES_ERROR_AS_NOTICE didn't include a PQclear, but now it does and so
 these other ones are duplicate.

---
 contrib/dblink/dblink.c | 14 +++++---------
 1 file changed, 5 insertions(+), 9 deletions(-)

diff --git a/contrib/dblink/dblink.c b/contrib/dblink/dblink.c
index 17f36f1306d..2b33043c5a2 100644
--- a/contrib/dblink/dblink.c
+++ b/contrib/dblink/dblink.c
@@ -345,7 +345,6 @@ dblink_open(PG_FUNCTION_ARGS)
 		else
 		{
 			DBLINK_RES_ERROR_AS_NOTICE("sql error");
-			PQclear(res);
 			PG_RETURN_TEXT_P(GET_TEXT("ERROR"));
 		}
 	}
@@ -419,7 +418,6 @@ dblink_close(PG_FUNCTION_ARGS)
 		else
 		{
 			DBLINK_RES_ERROR_AS_NOTICE("sql error");
-			PQclear(res);
 			PG_RETURN_TEXT_P(GET_TEXT("ERROR"));
 		}
 	}
@@ -531,8 +529,6 @@ dblink_fetch(PG_FUNCTION_ARGS)
 				DBLINK_RES_ERROR("sql error");
 			else
 			{
-				if (res)
-					PQclear(res);
 				DBLINK_RES_ERROR_AS_NOTICE("sql error");
 				SRF_RETURN_DONE(funcctx);
 			}
@@ -720,11 +716,9 @@ dblink_record(PG_FUNCTION_ARGS)
 				DBLINK_RES_ERROR("sql error");
 			else
 			{
-				if (res)
-					PQclear(res);
+				DBLINK_RES_ERROR_AS_NOTICE("sql error");
 				if (freeconn)
 					PQfinish(conn);
-				DBLINK_RES_ERROR_AS_NOTICE("sql error");
 				SRF_RETURN_DONE(funcctx);
 			}
 		}
@@ -938,13 +932,15 @@ dblink_exec(PG_FUNCTION_ARGS)
 		 * result tuple
 		 */
 		sql_cmd_status = GET_TEXT(PQcmdStatus(res));
+		PQclear(res);
 	}
 	else
+	{
+		PQclear(res);
 		ereport(ERROR,
 			  (errcode(ERRCODE_S_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED),
 			   errmsg("statement returning results not allowed")));
-
-	PQclear(res);
+	}
 
 	/* if needed, close the connection to the database and cleanup */
 	if (freeconn)
-- 
GitLab