Re: Should I free this memory?

Поиск
Список
Период
Сортировка
От Tom Lane
Тема Re: Should I free this memory?
Дата
Msg-id 1049.1303528316@sss.pgh.pa.us
обсуждение исходный текст
Ответ на Should I free this memory?  (Jorge Arévalo <jorge.arevalo@deimos-space.com>)
Ответы Re: Should I free this memory?  (Jorge Arévalo <jorge.arevalo@deimos-space.com>)
Список pgsql-general
=?ISO-8859-1?Q?Jorge_Ar=E9valo?= <jorge.arevalo@deimos-space.com> writes:
> old_context = MemoryContextSwitchTo(fcinfo->flinfo->fn_mcxt);
> p = palloc(100);
> MemoryContextSwitchTo(old_context);

Why are you doing that?

> Should I free the memory allocated for p? I'm getting memory leaks
> when I don't free the memory, and they disappear when I call pfree(p);

If you allocate that space again on every call, yes you'll get leaks.
The fn_mcxt context typically has query lifespan, and could be even
longer lived than that.

While you could fix it with a pfree at the end of the function, you'll
still have a leak if you lose control partway through due to some
function throwing an elog(ERROR).  By and large, if you intend to
allocate the space again on every call anyway, you should just palloc it
in your calling memory context, which has got tuple-cycle lifespan and
so doesn't pose much risk of bloat.  The only reason to allocate
something in fn_mcxt is if you're trying to cache data across successive
function calls.

            regards, tom lane

В списке pgsql-general по дате отправления:

Предыдущее
От: Tom Lane
Дата:
Сообщение: Re: What is this doing? SELECT (a,b,c) FROM mytable ...
Следующее
От: "Henry C."
Дата:
Сообщение: 20110408pg_upgrade_fix and "FATAL: could not access status of transaction..."