PostgreSQL allocates memory within memory
contexts, which provide a convenient method of
managing allocations made in many different places that need to live
for differing amounts of time. Destroying a context releases all the
memory that was allocated in it. Thus, it is not necessary to keep track
of individual objects to avoid memory leaks --- only a relatively small number
of contexts have to be managed. palloc and related
functions allocate memory from the "current" context.
SPI_connect creates a new memory context and makes
it current. SPI_finish restores the previous
current memory context and destroys the context created by
SPI_connect. These actions ensure that transient
memory allocations made inside your procedure are reclaimed at procedure
exit, avoiding memory leakage.
However, if your procedure needs to return an allocated memory object
(such as a value of a pass-by-reference data type), you can't allocate
the return object using palloc, at least not while
you are connected to SPI. If you try, the object will be deallocated
during SPI_finish, and your procedure will not
To solve this problem, use SPI_palloc to allocate
your return object. SPI_palloc allocates space
from "upper Executor" memory --- that is, the memory context
that was current when SPI_connect was called,
which is precisely the right context for return values of your procedure.
If called while not connected to SPI, SPI_palloc
acts the same as plain palloc.
Before a procedure connects to the SPI manager, the current memory context
is the upper Executor context, so all allocations made by the procedure via
palloc or by SPI utility functions are
made in this context.
After SPI_connect is called, the current context is
the procedure's private context made by SPI_connect.
All allocations made via
palloc/repalloc or by SPI utility
functions (except for SPI_copytuple,
and SPI_palloc) are
made in this context.
When a procedure disconnects from the SPI manager (via
current context is restored to the upper Executor context, and all allocations
made in the procedure memory context are freed and can't be used any more!
All functions described in this section may be used by both connected and
unconnected procedures. In an unconnected procedure, they act the same
as the underlying ordinary backend functions (palloc etc).