From a7e383d241581855cf7b4d6d6defa90444055e90 Mon Sep 17 00:00:00 2001
From: Tom Lane <tgl@sss.pgh.pa.us>
Date: Wed, 17 Dec 2003 20:15:41 +0000
Subject: [PATCH] Repair badly broken estimation of output buffer size in
 lquery_out().

---
 contrib/ltree/ltree_io.c | 9 ++++-----
 1 file changed, 4 insertions(+), 5 deletions(-)

diff --git a/contrib/ltree/ltree_io.c b/contrib/ltree/ltree_io.c
index 62c033cc5df..99803059f0f 100644
--- a/contrib/ltree/ltree_io.c
+++ b/contrib/ltree/ltree_io.c
@@ -498,22 +498,21 @@ lquery_out(PG_FUNCTION_ARGS)
 			   *ptr;
 	int			i,
 				j,
-				totallen = 0;
+				totallen = 1;
 	lquery_level *curqlevel;
 	lquery_variant *curtlevel;
 
 	curqlevel = LQUERY_FIRST(in);
 	for (i = 0; i < in->numlevel; i++)
 	{
+		totallen++;
 		if (curqlevel->numvar)
-			totallen = (curqlevel->numvar * 4) + 1 + curqlevel->totallen;
+			totallen += 1 + (curqlevel->numvar * 4) + curqlevel->totallen;
 		else
-			totallen = 2 * 11 + 4;
-		totallen++;
+			totallen += 2 * 11 + 4;
 		curqlevel = LQL_NEXT(curqlevel);
 	}
 
-
 	ptr = buf = (char *) palloc(totallen);
 	curqlevel = LQUERY_FIRST(in);
 	for (i = 0; i < in->numlevel; i++)
-- 
GitLab