Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA384:256) (Exim 4.89) (envelope-from ) id 1esZgK-0005j2-Rz for pgsql-general@arkaria.postgresql.org; Sun, 04 Mar 2018 19:52:28 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.89) (envelope-from ) id 1esZgJ-0006rh-5E for pgsql-general@arkaria.postgresql.org; Sun, 04 Mar 2018 19:52:27 +0000 Received: from makus.postgresql.org ([2001:4800:1501:1::229]) by malur.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA384:256) (Exim 4.89) (envelope-from ) id 1esZgI-0006rY-QA for pgsql-general@lists.postgresql.org; Sun, 04 Mar 2018 19:52:26 +0000 Received: from sss.pgh.pa.us ([66.207.139.130]) by makus.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA384:256) (Exim 4.89) (envelope-from ) id 1esZgB-0002wB-Bi for pgsql-general@lists.postgresql.org; Sun, 04 Mar 2018 19:52:25 +0000 Received: from sss1.sss.pgh.pa.us (localhost [127.0.0.1]) by sss.pgh.pa.us (8.14.4/8.14.4) with ESMTP id w24JqEGK026393; Sun, 4 Mar 2018 14:52:14 -0500 From: Tom Lane To: Albrecht =?iso-8859-1?b?RHJl3w==?= cc: pgsql-general@lists.postgresql.org Subject: Re: Q: text palloc() size vs. SET_VARSIZE() In-reply-to: References: Comments: In-reply-to Albrecht =?iso-8859-1?b?RHJl3w==?= message dated "Sun, 04 Mar 2018 18:48:10 +0100" MIME-Version: 1.0 Content-Type: text/plain; charset="us-ascii" Content-ID: <26391.1520193134.1@sss.pgh.pa.us> Content-Transfer-Encoding: quoted-printable Date: Sun, 04 Mar 2018 14:52:14 -0500 Message-ID: <26392.1520193134@sss.pgh.pa.us> List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Precedence: bulk Albrecht =3D?iso-8859-1?b?RHJl3w=3D=3D?=3D write= s: > text *t =3D PG_GETARG_TEXT_PP(0); > size_t out_len =3D 0U; > // allocate to the max. possible output size > text *new_t =3D (text *) palloc(VARSIZE_ANY_EXHDR(t) + VARHDRSZ= ); > // copy data to VARDATA(new_t), and count bytes in out_len > // set output size which is out_len <=3D VARSIZE_ANY_EXHDR(t) > SET_VARSIZE(new_t, out_len + VARHDRSZ); > PG_RETURN_TEXT_P(new_t); That code looks fine to me. > From the docs, for me it is not clear whether the value assigned using = SET_VARSIZE() must be the *exact* size of the newly allocated return value= , or just the length of the text plus the header size. IOW would the code= above create a memory leak if out_len < VARSIZE_ANY_EXHDR(t)? No memory leak. Your returned value would have some wasted memory at the end of its palloc chunk, but function result values don't normally live long enough that that's worth worrying about. You could repalloc the result down to minimum size if you felt like it, but I think it'd largely be a waste of cycles. There are lots of similar examples in the core backend, and few if any bother with a repalloc. regards, tom lane