Re: PL/pgSQL caught exceptions leak memory?

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: Michael Fuhr <mike(at)fuhr(dot)org>
Cc: pgsql-hackers(at)postgresql(dot)org
Subject: Re: PL/pgSQL caught exceptions leak memory?
Date: 2006-02-22 16:42:34
Message-ID: 12680.1140626554@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

Michael Fuhr <mike(at)fuhr(dot)org> writes:
> Caught exceptions in PL/pgSQL appear to leak memory -- is that
> expected?

This looks a bit messy :-(. The problem is that if the controlled
statements within the BEGIN block leak any function-local memory
(ie, memory in the "SPI Proc" context of the plpgsql function), this
memory is not reclaimed before we continue execution of the function.

It seems almost impossible to guarantee that no such leaks will occur,
since we might be trying to catch an elog that could have been thrown
from anywhere. The only practical fix is to run the controlled
statements in a sub-context that could be freed after the PG_CATCH.

The reason that the code currently tries to run the controlled
statements in the same context it was using is that all
pass-by-reference variable values get allocated in the current context.
If this context is thrown away then we'd have dangling pointers, eg
consider

declare x text;
begin
...
begin
x := some-expression;
exception
... try to use value of x here ...

AFAICS, to make this work we'd have to modify plpgsql so that variable
values are stored in a separate sub-context distinct from what's used as
the "current memory context" while running statements. This is gonna be
fairly invasive, I fear, and I'm worried about the performance cost of
extra copying too.

Any better ideas out there?

regards, tom lane

In response to

Browse pgsql-hackers by date

  From Date Subject
Next Message Jim C. Nasby 2006-02-22 16:49:03 Re: Updated email signature
Previous Message Andrew Dunstan 2006-02-22 16:12:22 Re: windows / initdb oddness