combine-diff: fix leaking lost lines

The `cnt` variable tracks the number of lines in a patch diff. It can happen though that there are no newlines, in which case we'd still end up allocating our array of `sline`s. In fact, we always allocate it with `cnt + 2` entries: one extra entry for the deletion hunk at the end, and another entry that we don't seem to ever populate at all but acts as a kind of sentinel value. When we loop through the array to clear it at the end of this function we only loop until `lno < cnt`, and thus we may not end up releasing whatever the two extra `sline`s contain. While that shouldn't matter for the sentinel value, it does matter for the extra deletion hunk sline. Regardless of that, plug this memory leak by releasing both extra entries, which makes the logic a bit easier to reason about. While at it, fix the formatting of a local comment, which incidentally also provides the necessary context for why we overallocate the `sline` array. Signed-off-by: Patrick Steinhardt <ps@pks.im> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Patrick Steinhardt committed Nov 5, 2024 at 07:17 UTC 1981d1eb3ecdefd2cdc665184d366728721f76e5
2 files changed +4 -2
combine-diff.c
+3 -2
@@ -1185,7 +1185,8 @@ static void show_patch_diff(struct combine_diff_path *elem, int num_parent,
1185 result_file.ptr = result;
1186 result_file.size = result_size;
1187
1188 - /* Even p_lno[cnt+1] is valid -- that is for the end line number
1188 + /*
1189 + * Even p_lno[cnt+1] is valid -- that is for the end line number
1190 * for deletion hunk at the end.
1191 */
1192 CALLOC_ARRAY(sline[0].p_lno, st_mult(st_add(cnt, 2), num_parent));
@@ -1220,7 +1221,7 @@ static void show_patch_diff(struct combine_diff_path *elem, int num_parent,
1221 }
1222 free(result);
1223
1223 - for (lno = 0; lno < cnt; lno++) {
1224 + for (lno = 0; lno < cnt + 2; lno++) {
1225 if (sline[lno].lost) {
1226 struct lline *ll = sline[lno].lost;
1227 while (ll) {
t/t4038-diff-combined.sh
+1
@@ -5,6 +5,7 @@ test_description='combined diff'
5 GIT_TEST_DEFAULT_INITIAL_BRANCH_NAME=main
6 export GIT_TEST_DEFAULT_INITIAL_BRANCH_NAME
7
8 +TEST_PASSES_SANITIZE_LEAK=true
9 . ./test-lib.sh
10 . "$TEST_DIRECTORY"/lib-diff.sh
11