Subject: [PATCH] reftable/writer: fix memory leak when `padded_write()` fails

From: "Lidong Yan via GitGitGadget" <[email-masked]>
Date: Sat, 10 May 2025 03:50:30 +0000

From: Lidong Yan <[email-masked]>

In reftable/writer.c:padded_write(), if w->writer failed, zeroed
allocated in `reftable_calloc` will leak. w->writer could be
`reftable_write_data` in reftable/stack.c, and could fail due to
some write error. Simply add reftable_free(zeroed) will solve this
problem.

Signed-off-by: Lidong Yan <[email-masked]>
---
    reftable/writer: fix memory leak when padded_write() fails
    
    In reftable/writer.c:padded_write(), if w->writer failed, zeroed
    allocated in reftable_calloc will leak. w->writer could be
    reftable_write_data in reftable/stack.c, and could fail due to some
    write error. Simply add reftable_free(zeroed) will solve this problem.

Published-As: https://github.com/gitgitgadget/git/releases/tag/pr-git-1958%2Fbrandb97%2Ffix-reftable-padded-write-leak-v1
Fetch-It-Via: git fetch https://github.com/gitgitgadget/git pr-git-1958/brandb97/fix-reftable-padded-write-leak-v1
Pull-Request: https://github.com/git/git/pull/1958

 reftable/writer.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)

diff --git a/reftable/writer.c b/reftable/writer.c
index cb16f71be49..3ceb3742888 100644
--- a/reftable/writer.c
+++ b/reftable/writer.c
@@ -57,8 +57,10 @@ static int padded_write(struct reftable_writer *w, uint8_t *data, size_t len,
 			return -1;
 
 		n = w->write(w->write_arg, zeroed, w->pending_padding);
-		if (n < 0)
+		if (n < 0) {
+			reftable_free(zeroed);
 			return n;
+		}
 
 		w->pending_padding = 0;
 		reftable_free(zeroed);

base-commit: 6f84262c44a89851c3ae5a6e4c1a9d06b2068d75
-- 
gitgitgadget