Subject: [PATCH v3 1/3] strbuf: fix incorrect alloc size in strbuf_reencode()

From: "Vaidas Pilkauskas via GitGitGadget" <[email-masked]>
Date: Tue, 17 Feb 2026 11:08:38 +0000

From: Vaidas Pilkauskas <[email-masked]>

The strbuf_reencode() function incorrectly passes the string length
as the allocation size to strbuf_attach(), when it should pass
length + 1 to account for the null terminator.

The reencode_string_len() function allocates len + 1 bytes (including
the null terminator) and returns the string length (excluding the null
terminator) via the len parameter. However, strbuf_reencode() then
calls strbuf_attach() with this length value as both the len and alloc
parameters:

    strbuf_attach(sb, out, len, len);

This is incorrect because strbuf_attach()'s alloc parameter should
reflect the actual allocated buffer size, which includes space for the
null terminator. This could lead to incorrect memory management in code
that relies on sb->alloc being accurate.

Fix by passing len + 1 as the alloc parameter:

    strbuf_attach(sb, out, len, len + 1);

Signed-off-by: Vaidas Pilkauskas <[email-masked]>
---
 strbuf.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/strbuf.c b/strbuf.c
index 3939863cf3..3e04addc22 100644
--- a/strbuf.c
+++ b/strbuf.c
@@ -168,7 +168,7 @@ int strbuf_reencode(struct strbuf *sb, const char *from, const char *to)
 	if (!out)
 		return -1;
 
-	strbuf_attach(sb, out, len, len);
+	strbuf_attach(sb, out, len, len + 1);
 	return 0;
 }
 
-- 
gitgitgadget