Re: Memory leak in pg_stat_statements when qtext file contains invalid encoding
Lukas Fittl <lukas@fittl.com>
From: Lukas Fittl <lukas@fittl.com>
To: Gaurav Singh <gaurav.singh@yugabyte.com>
Cc: pgsql-bugs@lists.postgresql.org
Date: 2026-03-27T08:21:39Z
Lists: pgsql-bugs
Hi Gaurav, On Fri, Mar 27, 2026 at 12:54 AM Gaurav Singh <gaurav.singh@yugabyte.com> wrote: > If the qtext file contains an invalid encoding, pg_any_to_server calls ereport(ERROR) which longjmps out of the function. > The cleanup code at the bottom of the function is never reached. > > LWLockRelease(pgss->lock); > if (qbuffer) > free(qbuffer); > On every subsequent call, the malloc'd buffer (the entire file contents) is leaked, and the LWLock release is also skipped. I don't think the analysis is correct in regards to the LWLock release - that should be taken care of by LWLockReleaseAll on abort. But I think you're correct about qbuffer - because that buffer is using malloc (not palloc), its not part of any memory context, and so it will happily leak on abort. It appears our use of malloc in pg_stat_statements is so that we can fail on OOM and return NULL without a jump. I think that makes sense for when a GC cycle was triggered during regular query execution (since we don't want to error the original query), but it seems like just bubbling up the OOM if needed when querying the pg_stat_statements function seems fine. I wonder if its worth separating the two cases, since the issue you're describing (the call to pg_any_to_server failing) only happens when returning the query text file contents to the client. I think your PG_FINALLY suggestion could also work, but it feels a bit tedious to wrap the whole pg_stat_statements_internal function in it. Thanks, Lukas PS: I would recommend reviewing the use of a text format email client for posting to the Postgres mailing lists, or significantly reducing your formatting when sending HTML emails - your email has a lot of styling that is hard to read (even for me in Gmail), and even harder to quote in a plain text email response. -- Lukas Fittl
Commits
-
Avoid memory leak on error while parsing pg_stat_statements dump file
- 3c74cb5762db 19 (unreleased) landed
- a6d03067ff5d 14.23 landed
- 92cf11171baf 15.18 landed
- 52edaf9d9b02 16.14 landed
- 351e59f344b5 17.10 landed
- 25b02320e133 18.4 landed