wt-status: fix leaking buffer with sparse directories

When hitting a sparse directory in `wt_status_collect_changes_initial()` we use a `struct strbuf` to assemble the directory's name. We never free that buffer though, causing a memory leak. Fix the leak by releasing the buffer. While at it, move the buffer outside of the loop and reset it to save on some wasteful allocations. Signed-off-by: Patrick Steinhardt <ps@pks.im> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Patrick Steinhardt committed Sep 30, 2024 at 11:13 UTC 666643fa89e4386c0f4eabd1112e8b3af0cb9cc1
2 files changed +6 -1
t/t1092-sparse-checkout-compatibility.sh
+1
@@ -5,6 +5,7 @@ test_description='compare full workdir to sparse workdir'
5 GIT_TEST_SPLIT_INDEX=0
6 GIT_TEST_SPARSE_INDEX=
7
8 +TEST_PASSES_SANITIZE_LEAK=true
9 . ./test-lib.sh
10
11 test_expect_success 'setup' '
wt-status.c
+5 -1
@@ -717,6 +717,7 @@ static int add_file_to_list(const struct object_id *oid,
717 static void wt_status_collect_changes_initial(struct wt_status *s)
718 {
719 struct index_state *istate = s->repo->index;
720 + struct strbuf base = STRBUF_INIT;
721 int i;
722
723 for (i = 0; i < istate->cache_nr; i++) {
@@ -735,7 +736,6 @@ static void wt_status_collect_changes_initial(struct wt_status *s)
736 * expanding the trees to find the elements that are new in this
737 * tree and marking them with DIFF_STATUS_ADDED.
738 */
738 - struct strbuf base = STRBUF_INIT;
739 struct pathspec ps = { 0 };
740 struct tree *tree = lookup_tree(istate->repo, &ce->oid);
741
@@ -743,9 +743,11 @@ static void wt_status_collect_changes_initial(struct wt_status *s)
743 ps.has_wildcard = 1;
744 ps.max_depth = -1;
745
746 + strbuf_reset(&base);
747 strbuf_add(&base, ce->name, ce->ce_namelen);
748 read_tree_at(istate->repo, tree, &base, 0, &ps,
749 add_file_to_list, s);
750 +
751 continue;
752 }
753
@@ -772,6 +774,8 @@ static void wt_status_collect_changes_initial(struct wt_status *s)
774 s->committable = 1;
775 }
776 }
777 +
778 + strbuf_release(&base);
779 }
780
781 static void wt_status_collect_untracked(struct wt_status *s)