format-patch: unleak "-v <num>"

The "subject_prefix" member of "struct revision" usually is set to a borrowed string (either a string literal like "PATCH" that appear in the program text as a hardcoded default, or the value of "format.subjectprefix") and is never freed when the containing revision structure is released. The "-v <num>" codepath however violates this rule and stores a pointer to an allocated string to this member, relinquishing the responsibility to free it when it is done using the revision structure, leading to a small one-time leak. Instead, keep track of the string it allocates to let the revision structure borrow, and clean it up when it is done. Signed-off-by: Junio C Hamano <gitster@pobox.com>

Junio C Hamano committed Jan 15, 2023 at 00:03 UTC 5b8db44bdd619dc5ec4dcdac5cb3ca194ebdd046
1 file changed +3 -3
builtin/log.c
+3 -3
@@ -1870,6 +1870,7 @@ int cmd_format_patch(int argc, const char **argv, const char *prefix)
1870 struct strbuf rdiff1 = STRBUF_INIT;
1871 struct strbuf rdiff2 = STRBUF_INIT;
1872 struct strbuf rdiff_title = STRBUF_INIT;
1873 + struct strbuf sprefix = STRBUF_INIT;
1874 int creation_factor = -1;
1875
1876 const struct option builtin_format_patch_options[] = {
@@ -2010,12 +2011,10 @@ int cmd_format_patch(int argc, const char **argv, const char *prefix)
2011 cover_from_description_mode = parse_cover_from_description(cover_from_description_arg);
2012
2013 if (reroll_count) {
2013 - struct strbuf sprefix = STRBUF_INIT;
2014 -
2014 strbuf_addf(&sprefix, "%s v%s",
2015 rev.subject_prefix, reroll_count);
2016 rev.reroll_count = reroll_count;
2018 - rev.subject_prefix = strbuf_detach(&sprefix, NULL);
2017 + rev.subject_prefix = sprefix.buf;
2018 }
2019
2020 for (i = 0; i < extra_hdr.nr; i++) {
@@ -2376,6 +2375,7 @@ done:
2375 strbuf_release(&rdiff1);
2376 strbuf_release(&rdiff2);
2377 strbuf_release(&rdiff_title);
2378 + strbuf_release(&sprefix);
2379 free(to_free);
2380 if (rev.ref_message_ids)
2381 string_list_clear(rev.ref_message_ids, 0);