Re: Should I free this memory?

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: Jorge Arévalo <jorge(dot)arevalo(at)deimos-space(dot)com>
Cc: pgsql-general <pgsql-general(at)postgresql(dot)org>
Subject: Re: Should I free this memory?
Date: 2011-04-23 03:11:56
Message-ID: 1049.1303528316@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

=?ISO-8859-1?Q?Jorge_Ar=E9valo?= <jorge(dot)arevalo(at)deimos-space(dot)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

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Henry C. 2011-04-23 07:56:57 20110408pg_upgrade_fix and "FATAL: could not access status of transaction..."
Previous Message Tom Lane 2011-04-23 03:05:08 Re: What is this doing? SELECT (a,b,c) FROM mytable ...