[postgis-devel] Question on memory management on C functions

Jorge Arévalo jorge.arevalo at deimos-space.com
Sun Apr 24 05:29:13 PDT 2011


I've read http://trac.osgeo.org/postgis/wiki/DevWikiPostGISCoding, and
I have a doubt:

Inside "postgis" dir, all the calls to lwalloc are really calls to
palloc, because lwallocators are set to palloc family functions. So,
as far as you work inside calling function memory context, you
shouldn't need to free the memory, because PostgreSQL will clean it up
after the end of the function.

I've seen in many functions (like shortestline2d) the memory is not
released when errors happen.  You don't call any release function
before calling PG_RETURN_NULL, for example. But when everything goes
ok, the memory is free'd before returning the value (calls to lwfree,
PG_FREE_IT_COPY, etc). Why?

I have an unconfirmed theory: a PG_RETURN_NULL call means the end of
the function. So, all the memory is automatically released (but the
long-life memory, stored in contexts like fcinfo->flinfo->fn_mcxt or
multi_call_memory_ctx). That not necessarily happens when the function
returns a valid value.

An example: ST_ShortestLine function. It calls LWGEOM_shortestline2d
function. The function returns a PG_LWGEOM object, but after finishing
the ST_Shortestline function and returns its value, still a call to
LWGEOM_out is needed. So, all the memory allocated in
LWGEOM_shortestline2d is released at the end of the function.

But I repit my question: Why? I guess is a question of "keeping the
house clear". All the memory will be finally released, but LWGEOM_out
function will allocate more memory, and the memory used in
LWGEOM_shortestline2d function is no longer necessary. Why to expect
PostgreSQL cleaner?

Am I right?

Many thanks in advance,

Jorge Arévalo
Internet & Mobilty Division, DEIMOS
jorge.arevalo at deimos-space.com

More information about the postgis-devel mailing list