From 3e4344be5410b365d897710639fed6025ec76f4c Mon Sep 17 00:00:00 2001
From: ocean-dot-li <ocean_li_996@163.com>
Date: Thu, 16 Nov 2023 16:40:57 +0800
Subject: [PATCH] [Bug] fix log buffer inital issue

In exec_execute_message(), we should initalize the log buffer at
outermost layer. If not, crash may happen when trying to accessing
its data member.

This patch fixes the issue.
---
 src/backend/tcop/postgres.c | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)

diff --git a/src/backend/tcop/postgres.c b/src/backend/tcop/postgres.c
index 02a5b3992de..f7f6c98ffff 100644
--- a/src/backend/tcop/postgres.c
+++ b/src/backend/tcop/postgres.c
@@ -2354,13 +2354,17 @@ exec_execute_message(const char *portal_name, long max_rows)
 			pq_putemptymessage('s');
 	}
 
+	buf.data = NULL;
+
 	if (to_log)
 	{
 	    /* POLAR: get errmsg params string, we must free it in the last */
 		// It needs to malloc and free twice, not so efficiency.
 	    params_string = polar_get_errmsg_params(portalParams);
 	
+		/* POLAR: inital buf used by logging info. */
 		initStringInfo(&buf);
+
 		if (polar_enable_log_search_path)
 			appendStringInfo(&buf, "/*polardb %s polardb*/ ", namespace_search_path);
 
@@ -2491,7 +2495,7 @@ exec_execute_message(const char *portal_name, long max_rows)
   		pfree(params_string);
   	/* POLAR end */
 
-	if (buf.data)
+	if (to_log && buf.data)
 		pfree(buf.data);
 
   	if (save_log_statement_stats)