[PATCH] Fix memory leak of reply_message in walreceiver
DaeMyung Kang <charsyam@gmail.com>
From: DaeMyung Kang <charsyam@gmail.com>
To: pgsql-hackers@lists.postgresql.org
Cc: DaeMyung Kang <charsyam@gmail.com>
Date: 2026-04-26T16:59:09Z
Lists: pgsql-hackers
Attachments
- 0001-Fix-memory-leak-of-reply_message-in-walreceiver.patch (text/x-patch) patch 0001
Hi, Hackers,
While reading walreceiver.c, I noticed that the static StringInfoData
reply_message gets initialized inside the outer streaming loop in
WalReceiverMain(), specifically right after walrcv_startstreaming()
succeeds:
/* Initialize LogstreamResult and buffers for processing messages */
LogstreamResult.Write = LogstreamResult.Flush = GetXLogReplayRecPtr(NULL);
initStringInfo(&reply_message);
initStringInfo() unconditionally allocates a fresh ~1KB buffer with
palloc() and overwrites the existing data pointer without freeing the
previous one. So every time the walreceiver re-enters the streaming
path -- e.g., after a timeline switch, end-of-WAL, or any other
condition that drives the outer for(;;) loop to iterate -- the prior
buffer is leaked. The leak is bounded per streaming restart but
accumulates over the lifetime of a long-running standby that
restarts streaming often.
Subsequent uses of reply_message already call resetStringInfo() to
reuse the buffer, so a single one-time initialization before the
outer loop is sufficient. The attached patch moves the call up and
adjusts the comment accordingly.
This appears to date back to commit add6c3179a4 ("Make the streaming
replication protocol messages architecture-independent.", 2012), so
the fix is likely a candidate for back-patching to all supported
branches.
No new tests are added; the fix only releases resources and does not
change observable behavior. `make check` and the streaming replication
TAP test (src/test/recovery/t/001_stream_rep.pl) pass with the patch
applied.
Patch attached.
Regards,
DaeMyung Kang
Commits
Same data as JSON:
GET /api/v1/messages/:b64id/commits
the thread's linked commits as JSON, with link sources.
API reference →
-
Fix some memory leaks in the WAL receiver
- b801d5eef17f 19 (unreleased) landed
-
Make the streaming replication protocol messages architecture-independent.
- add6c3179a4d 9.3.0 cited