Fix memory leak in repeated SPGIST index scans.
authorTom Lane <[email protected]>
Wed, 31 Oct 2018 21:04:43 +0000 (17:04 -0400)
committerTom Lane <[email protected]>
Wed, 31 Oct 2018 21:04:43 +0000 (17:04 -0400)
spgendscan neglected to pfree all the memory allocated by spgbeginscan.
It's possible to get away with that in most normal queries, since the
memory is allocated in the executor's per-query context which is about
to get deleted anyway; but it causes severe memory leakage during
creation or filling of large exclusion-constraint indexes.

Also, document that amendscan is supposed to free what ambeginscan
allocates.  The docs' lack of clarity on that point probably caused this
bug to begin with.  (There is discussion of changing that API spec going
forward, but I don't think it'd be appropriate for the back branches.)

Per report from Bruno Wolff.  It's been like this since the beginning,
so back-patch to all active branches.

In HEAD, also fix an independent leak caused by commit 2a6368343
(allocating memory during spgrescan instead of spgbeginscan, which
might be all right if it got cleaned up, but it didn't).  And do a bit
of code beautification on that commit, too.

Discussion: https://postgr.es/m/20181024012314[email protected]

doc/src/sgml/indexam.sgml
src/backend/access/spgist/spgscan.c

index 157047a23ab15ab86204db66b9e38d0aa64fae2f..faf890abd614a2135bc4320d29a64550b7658dfa 100644 (file)
@@ -455,7 +455,8 @@ amendscan (IndexScanDesc scan);
 </programlisting>
    End a scan and release resources.  The <literal>scan</> struct itself
    should not be freed, but any locks or pins taken internally by the
-   access method must be released.
+   access method must be released, as well as any other memory allocated
+   by <function>ambeginscan</function> and other scan-related functions.
   </para>
 
   <para>
index 35cc41b3aabbea9cdf5908f2dc27ea4d2005e1a4..21871dbfc1d8380d35f10f50f712d6636d89fcdf 100644 (file)
@@ -236,6 +236,14 @@ spgendscan(PG_FUNCTION_ARGS)
 
    MemoryContextDelete(so->tempCxt);
 
+   if (so->keyData)
+       pfree(so->keyData);
+
+   if (so->state.deadTupleStorage)
+       pfree(so->state.deadTupleStorage);
+
+   pfree(so);
+
    PG_RETURN_VOID();
 }