[C-function] Can SET_VARSIZE cause a memory leak?

Started by Nick Babadzhanianalmost 10 years ago3 messagesgeneral
Jump to latest

I didn't find an easy way to convert ucs-2 bytea to utf-8, so I decided to write a C-function. Since ucs-2 is has fixed symbol size of 2 bytes the output bytea size may differ.

I do the following:

bytea *result= (bytea *) palloc0(VARSIZE(in_bytea)); // allocating memory for the result
SET_VARSIZE(result, VARSIZE_ANY(in_bytea));

... // some calculations resulting in `result` having some trailing 0-s (since palloc0 was used). We don't need those, so:

SET_VARSIZE(result, new_varsize_result+VARHDRSZ); // new_varsize_result was calculated during the convertion

PG_RETURN_BYTEA_P(result);

The question is am I leaking memory by doing this, and if I am, should I use pfree() manually on each address that is left trailing, or is there some other way to make this work?

Regards,
Nick.

--
Sent via pgsql-general mailing list (pgsql-general@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-general

#2Laurenz Albe
laurenz.albe@cybertec.at
In reply to: Nick Babadzhanian (#1)
Re: Can SET_VARSIZE cause a memory leak?

Николай Бабаджанян wrote:

I didn't find an easy way to convert ucs-2 bytea to utf-8, so I decided to write a C-function. Since
ucs-2 is has fixed symbol size of 2 bytes the output bytea size may differ.

I do the following:

bytea *result= (bytea *) palloc0(VARSIZE(in_bytea)); // allocating memory for the result
SET_VARSIZE(result, VARSIZE_ANY(in_bytea));

... // some calculations resulting in `result` having some trailing 0-s (since palloc0 was
used). We don't need those, so:

SET_VARSIZE(result, new_varsize_result+VARHDRSZ); // new_varsize_result was calculated during
the convertion

PG_RETURN_BYTEA_P(result);

The question is am I leaking memory by doing this, and if I am, should I use pfree() manually on each
address that is left trailing, or is there some other way to make this work?

This is safe, and the memory will be freed at the end of the transaction.

Yours,
Laurenz Albe

--
Sent via pgsql-general mailing list (pgsql-general@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-general

#3Michael Paquier
michael@paquier.xyz
In reply to: Laurenz Albe (#2)
Re: Can SET_VARSIZE cause a memory leak?

On Wed, Jun 8, 2016 at 9:55 PM, Albe Laurenz <laurenz.albe@wien.gv.at> wrote:

This is safe, and the memory will be freed at the end of the transaction.

Yes, palloc takes memory from the current memory context. The case
where you would need to use pfree is if there is an allocation
continuously done within the same code paths for a reason or another
that may result in a leak if this code path is taken repeatedly and
that the memory used is wasted out.
--
Michael

--
Sent via pgsql-general mailing list (pgsql-general@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-general