From 19c8c53949959a0bac2408268d8709c8930e042d Mon Sep 17 00:00:00 2001
From: interma <interma@outlook.com>
Date: Mon, 11 Sep 2023 14:42:14 +0800
Subject: [PATCH] Using long type in printTableAddCell() to prevent int
 overflow

---
 src/fe_utils/print.c | 26 ++++++++++++++++++--------
 1 file changed, 18 insertions(+), 8 deletions(-)

diff --git a/src/fe_utils/print.c b/src/fe_utils/print.c
index 7af1ccb6b5..5c0748df10 100644
--- a/src/fe_utils/print.c
+++ b/src/fe_utils/print.c
@@ -3172,6 +3172,8 @@ void
 printTableInit(printTableContent *const content, const printTableOpt *opt,
 			   const char *title, const int ncolumns, const int nrows)
 {
+	long total_cells;
+
 	content->opt = opt;
 	content->title = title;
 	content->ncolumns = ncolumns;
@@ -3179,7 +3181,8 @@ printTableInit(printTableContent *const content, const printTableOpt *opt,
 
 	content->headers = pg_malloc0((ncolumns + 1) * sizeof(*content->headers));
 
-	content->cells = pg_malloc0((ncolumns * nrows + 1) * sizeof(*content->cells));
+	total_cells = (long)ncolumns * (long)nrows;
+	content->cells = pg_malloc0((total_cells + 1) * sizeof(*content->cells));
 
 	content->cellmustfree = NULL;
 	content->footers = NULL;
@@ -3249,15 +3252,21 @@ void
 printTableAddCell(printTableContent *const content, char *cell,
 				  const bool translate, const bool mustfree)
 {
+	long total_cells;
 #ifndef ENABLE_NLS
 	(void) translate;			/* unused parameter */
 #endif
 
-	if (content->cellsadded >= content->ncolumns * content->nrows)
+	/*
+	 * total_cells is the product of ncolumns and nrows
+	 * Using long type here to prevent int overflow
+	 */
+	total_cells = (long)content->ncolumns * (long)content->nrows;
+	if (content->cellsadded >= total_cells)
 	{
 		fprintf(stderr, _("Cannot add cell to table content: "
-						  "total cell count of %d exceeded.\n"),
-				content->ncolumns * content->nrows);
+						  "total cell count of %ld exceeded, cells added: %ld.\n"),
+				total_cells, content->cellsadded);
 		exit(EXIT_FAILURE);
 	}
 
@@ -3273,7 +3282,7 @@ printTableAddCell(printTableContent *const content, char *cell,
 	{
 		if (content->cellmustfree == NULL)
 			content->cellmustfree =
-				pg_malloc0((content->ncolumns * content->nrows + 1) * sizeof(bool));
+				pg_malloc0((total_cells + 1) * sizeof(bool));
 
 		content->cellmustfree[content->cellsadded] = true;
 	}
@@ -3341,9 +3350,10 @@ printTableCleanup(printTableContent *const content)
 {
 	if (content->cellmustfree)
 	{
-		int			i;
-
-		for (i = 0; i < content->nrows * content->ncolumns; i++)
+		long		i;
+		long		total_cells;
+		total_cells = (long)content->ncolumns * (long)content->nrows;
+		for (i = 0; i < total_cells; i++)
 		{
 			if (content->cellmustfree[i])
 				free(unconstify(char *, content->cells[i]));
-- 
2.39.2 (Apple Git-143)

