[postgis-devel] Small memory leak in function BOX2D_to_LWGEOM

Raúl Marín raul at rmr.ninja
Sat Sep 10 06:32:29 PDT 2022


Hi,

For the most part, there is no need to free memory in PG functions as it 
will be freed once the allocation arena  as a whole is freed.

There are some exceptions, like when working with huge allocations, 
recursion (lots of allocations) or memory not handled by PG, but AFAICS 
this one is not one of those.

In any case, if you actually detect the leak and have a way to reproduce 
it it'd be worth investigating, because this or similar patterns are 
present in many other functions.

El 10/09/2022 a las 9:48, Esteban Zimanyi escribió:
> PG_FUNCTION_INFO_V1(BOX2D_to_LWGEOM);
> Datum BOX2D_to_LWGEOM(PG_FUNCTION_ARGS)
> {
>    GBOX *box = (GBOX *)PG_GETARG_POINTER(0);
>    POINTARRAY *pa = ptarray_construct_empty(0, 0, 5); // <----------------
>    POINT4D pt;
>    GSERIALIZED *result;
>
>    /* ...  */
>
>    if ( (box->xmin == box->xmax) && (box->ymin == box->ymax) )
>    {
>      /* pa is NOT used */;
>      ...
>    }
>    else if ( (box->xmin == box->xmax) || (box->ymin == box->ymax) )
>    {
>      /* ONLY case where pa is used */;
>      ...
>    }
>    else
>    {
>      POINT4D points[4];
>      LWPOLY *poly;
>
>      /* Initialize the 4 vertices of the polygon */
>      ...
>
>      /* A new pa is created in the following function call <-------------- */;
>
>      /* Construct polygon */
>      poly = lwpoly_construct_rectangle(LW_FALSE, LW_FALSE, &points[0],
> &points[1],
>          &points[2], &points[3]);
>      result = geometry_serialize(lwpoly_as_lwgeom(poly));
>      lwpoly_free(poly);
>    }
>
>    PG_RETURN_POINTER(result);
> }
>
> A possible solution would be
>
> PG_FUNCTION_INFO_V1(BOX2D_to_LWGEOM);
> Datum BOX2D_to_LWGEOM(PG_FUNCTION_ARGS)
> {
>    GBOX *box = (GBOX *)PG_GETARG_POINTER(0);
>    // Declaration removed <-------------------------
>    POINT4D pt;
>    GSERIALIZED *result;
>
>    /* ... */
>
>    if ( (box->xmin == box->xmax) && (box->ymin == box->ymax) )
>    {
>      /* As before <----------------- */;
>      ...
>    }
>    else if ( (box->xmin == box->xmax) || (box->ymin == box->ymax) )
>    {
>      LWLINE *line;
>      POINTARRAY *pa = ptarray_construct_empty(0, 0, 2); //
> <-------------------------
>        ...
>    }
>    else
>    {
>      /* As before <----------------- */;
>      ...
> }
>
> PG_RETURN_POINTER(result);
> }
> _______________________________________________
> postgis-devel mailing list
> postgis-devel at lists.osgeo.org
> https://lists.osgeo.org/mailman/listinfo/postgis-devel


More information about the postgis-devel mailing list