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

From: Albrecht Dreß <albrecht(dot)dress(at)arcor(dot)de>
To: pgsql-general(at)lists(dot)postgresql(dot)org
Subject: Q: text palloc() size vs. SET_VARSIZE()
Date: 2018-03-04 17:48:10
Message-ID: I4NJ4KUY.YUJI5WKV.EDRTQQUJ@WDR6Z6G7.7HHA5U57.KVGNKQOS
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Hi all,

I have a (hopefully not too dumb) question regarding the size allocation of a text return value in a C user-defined function.

Basically, the function is somewhat similar to the copytext() example on <https://www.postgresql.org/docs/10/static/xfunc-c.html>. However, the function shall perform some “decoding” of the input text, so the result is either as long as the input, or shorter.

In order to avoid time-consuming double-scanning of the input or re-allocation of memory, the idea is to allocate the result to the maximum possible size, which may or may not be filled completely. Copied from the example in the manual:

---8<--------------------------------------------------------------------------
Datum
decode_text(PG_FUNCTION_ARGS)
{
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);
}
---8<--------------------------------------------------------------------------

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)?

If this approach is wrong, would it be possible in the example above to just re-size new_t to the correct size by calling repalloc()?

Thanks in advance,
Albrecht.

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Tom Lane 2018-03-04 19:52:14 Re: Q: text palloc() size vs. SET_VARSIZE()
Previous Message Vick Khera 2018-03-04 16:45:28 Re: Jira database won't start after disk filled up