Re: Q: text palloc() size vs. SET_VARSIZE()

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: Albrecht Dreß <albrecht(dot)dress(at)arcor(dot)de>
Cc: pgsql-general(at)lists(dot)postgresql(dot)org
Subject: Re: Q: text palloc() size vs. SET_VARSIZE()
Date: 2018-03-04 19:52:14
Message-ID: 26392.1520193134@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Albrecht =?iso-8859-1?b?RHJl3w==?= <albrecht(dot)dress(at)arcor(dot)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

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message raf 2018-03-04 22:58:29 Re: Is there a continuous backup for pg ?
Previous Message Albrecht Dreß 2018-03-04 17:48:10 Q: text palloc() size vs. SET_VARSIZE()