Freeing plan memory

From: "Nigel J(dot) Andrews" <nandrews(at)investsystems(dot)co(dot)uk>
To: pgsql-hackers(at)postgresql(dot)org
Subject: Freeing plan memory
Date: 2002-10-19 16:27:05
Message-ID: Pine.LNX.4.21.0210191646260.26324-100000@ponder.fairway2k.co.uk
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

I notice there's a leak of memory in SPI_prepare().

The full fix is nontrival and I don't want to submit a half solution so I
thought I'd check whether people think it's worth worrying about.

The leak is that memory is grabbed in SPI_prepare() for a plan within whatever
context is current when it does the palloc(). It may be the caller's or it may
be the relevent SPI one. The plan is then copied out of this memory [and
context] into a child of the procedure's context and forgotten about, or just
plain forgotten. Obviously the intention is that this memory is freed when the
context is deleted and is probably not a problem unless someone does something
like:

i = 100000;
while (i--)
{
plan = SPI_prepare("SELECT 1", 0, (Oid *)NULL);
SPI_freeplan(plan); /* SPI_freeplan() is not just for SPI_saveplan() */
}

Is this worth worrying about?

Any busy person can stop reading now as the above defines the problem while the
below only shows an easily reproducable example.

FWIW, I found it while testing something like, which is a little less daft
than the above example:

create function atest1 ( ) returns int as '
a = 0
while a < 10000:
plan = plpy.prepare("SELECT " + repr(a))
a = a + 1
' language 'plpython';

Here the plpython code uses SPI_freeplan to release the context holding the
plan memory when each plan object returned by plpy.prepare() is garbage
collected. This seems sensibly to happen when the plan variable is
reassigned. However I was baffled why the process still had an obvious memory
leak so looked a little closer at SPI.

--
Nigel J. Andrews

Responses

Browse pgsql-hackers by date

  From Date Subject
Next Message Tom Lane 2002-10-19 16:30:03 Re: Postgresql and multithreading
Previous Message Tom Lane 2002-10-19 16:16:53 Re: /contrib/retep to gborg