trailer: fix leaking strbufs when formatting trailers

We are populating, but never releasing two string buffers in
`format_trailers()`, causing a memory leak. Plug this leak by lifting
those buffers outside of the loop and releasing them on function return.
This fixes the memory leaks, but also optimizes the loop as we don't
have to reallocate the buffers on every single iteration.

Signed-off-by: Patrick Steinhardt <ps@pks.im>
Signed-off-by: Taylor Blau <me@ttaylorr.com>
This commit is contained in:
Patrick Steinhardt
2024-10-21 11:28:35 +02:00
committed by Taylor Blau
parent ecbb58e295
commit 9d0482d2a5
2 changed files with 9 additions and 5 deletions

View File

@@ -5,6 +5,7 @@
test_description='git interpret-trailers'
TEST_PASSES_SANITIZE_LEAK=true
. ./test-lib.sh
# When we want one trailing space at the end of each line, let's use sed

View File

@@ -1111,16 +1111,19 @@ void format_trailers(const struct process_trailer_options *opts,
struct list_head *trailers,
struct strbuf *out)
{
struct strbuf tok = STRBUF_INIT;
struct strbuf val = STRBUF_INIT;
size_t origlen = out->len;
struct list_head *pos;
struct trailer_item *item;
list_for_each(pos, trailers) {
item = list_entry(pos, struct trailer_item, list);
if (item->token) {
struct strbuf tok = STRBUF_INIT;
struct strbuf val = STRBUF_INIT;
strbuf_reset(&tok);
strbuf_addstr(&tok, item->token);
strbuf_reset(&val);
strbuf_addstr(&val, item->value);
/*
@@ -1151,9 +1154,6 @@ void format_trailers(const struct process_trailer_options *opts,
if (!opts->separator)
strbuf_addch(out, '\n');
}
strbuf_release(&tok);
strbuf_release(&val);
} else if (!opts->only_trailers) {
if (opts->separator && out->len != origlen) {
strbuf_addbuf(out, opts->separator);
@@ -1165,6 +1165,9 @@ void format_trailers(const struct process_trailer_options *opts,
strbuf_addch(out, '\n');
}
}
strbuf_release(&tok);
strbuf_release(&val);
}
void format_trailers_from_commit(const struct process_trailer_options *opts,