From cc2ba0b74a0b86b82181fbb1fa75d3ab953383cd Mon Sep 17 00:00:00 2001 From: Lucas De Marchi Date: Tue, 12 Nov 2024 13:43:20 -0600 Subject: [PATCH] strbuf: Do not append '\0' if not needed Unconditionally appending '\0' is not a big problem, but that does trigger the buffer to potentially be re-allocated. Avoid that by checking the last char is not already NUL. Signed-off-by: Lucas De Marchi Reviewed-by: Emil Velikov Link: https://github.com/kmod-project/kmod/pull/239 --- shared/strbuf.c | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/shared/strbuf.c b/shared/strbuf.c index 5a25976c..69d20db6 100644 --- a/shared/strbuf.c +++ b/shared/strbuf.c @@ -78,9 +78,11 @@ char *strbuf_steal(struct strbuf *buf) const char *strbuf_str(struct strbuf *buf) { - if (!strbuf_reserve_extra(buf, 1)) - return NULL; - buf->bytes[buf->used] = '\0'; + if (!buf->used || buf->bytes[buf->used - 1]) { + if (!strbuf_reserve_extra(buf, 1)) + return NULL; + buf->bytes[buf->used] = '\0'; + } return buf->bytes; } -- 2.47.2