Subject: [PATCH v4 3/5] strbuf: replace strbuf_grow() in strbuf_attach() with BUG() check

From: "Vaidas Pilkauskas via GitGitGadget" <[email-masked]>
Date: Wed, 18 Feb 2026 14:09:06 +0000

From: Vaidas Pilkauskas <[email-masked]>

strbuf_attach() documents that alloc must be larger than len, as the
buffer must have room for the NUL terminator. Replace the strbuf_grow(sb, 0)
call, which was silently reallocating when alloc <= len, with an explicit
BUG() to enforce this contract and write the NUL terminator directly.

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

diff --git a/strbuf.c b/strbuf.c
index 3e04addc22..0abed40c91 100644
--- a/strbuf.c
+++ b/strbuf.c
@@ -95,11 +95,12 @@ char *strbuf_detach(struct strbuf *sb, size_t *sz)
 
 void strbuf_attach(struct strbuf *sb, void *buf, size_t len, size_t alloc)
 {
+	if (alloc <= len)
+		BUG("alloc must be larger than len");
 	strbuf_release(sb);
 	sb->buf   = buf;
 	sb->len   = len;
 	sb->alloc = alloc;
-	strbuf_grow(sb, 0);
 	sb->buf[sb->len] = '\0';
 }
 
-- 
gitgitgadget