Re: Should I free this memory? - Mailing list pgsql-general

From Tom Lane
Subject Re: Should I free this memory?
Date
Msg-id 1049.1303528316@sss.pgh.pa.us
Whole thread Raw
In response to Should I free this memory?  (Jorge Arévalo <jorge.arevalo@deimos-space.com>)
Responses Re: Should I free this memory?
List 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 by date:

Previous
From: Tom Lane
Date:
Subject: Re: What is this doing? SELECT (a,b,c) FROM mytable ...
Next
From: "Henry C."
Date:
Subject: 20110408pg_upgrade_fix and "FATAL: could not access status of transaction..."