pg.ddx.io  pgsql-general@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Tom Lane <tgl@sss.pgh.pa.us>
To: Albrecht Dreß <albrecht.dress@arcor.de>
Cc: pgsql-general@lists.postgresql.org
Subject: Re: Q: text palloc() size vs. SET_VARSIZE()
Date: Sun, 04 Mar 2018 14:52:14 -0500
Message-ID: <26392.1520193134@sss.pgh.pa.us> (raw)
In-Reply-To: <I4NJ4KUY.YUJI5WKV.EDRTQQUJ@WDR6Z6G7.7HHA5U57.KVGNKQOS>
References: <I4NJ4KUY.YUJI5WKV.EDRTQQUJ@WDR6Z6G7.7HHA5U57.KVGNKQOS>

Albrecht =?iso-8859-1?b?RHJl3w==?= <albrecht.dress@arcor.de> writes:
>      text     *t = PG_GETARG_TEXT_PP(0);
>      size_t    out_len = 0U;

>      // allocate to the max. possible output size
>      text     *new_t = (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 <= 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




view thread (3+ messages)  latest in thread

Message-ID: <26392.1520193134@sss.pgh.pa.us>
Permalink:  ../26392.1520193134@sss.pgh.pa.us/
Also on:    postgresql.org/message-id/26392.1520193134@sss.pgh.pa.us

 · 

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients from your mail client; the link fills in
  the headers below: reply via email
  Some clients, webmail especially, drop In-Reply-To and References from
  a link, and the reply then starts a new thread: use the mbox below.

  To: pgsql-general@postgresql.org
  Cc: tgl@sss.pgh.pa.us, albrecht.dress@arcor.de
  Subject: Re: Q: text palloc() size vs. SET_VARSIZE()
  In-Reply-To: <26392.1520193134@sss.pgh.pa.us>
  References: <I4NJ4KUY.YUJI5WKV.EDRTQQUJ@WDR6Z6G7.7HHA5U57.KVGNKQOS> <26392.1520193134@sss.pgh.pa.us>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox