diff: refactor code to clarify memory ownership of prefixes
The source and destination prefixes are tracked in a `const char *` array, but may at times contain allocated strings. The result is that those strings may be leaking because we never free them. Refactor the code to always store allocated strings in those variables, freeing them as required. This requires us to handle the default values a bit different compared to before. But given that there is only a single callsite where we use the variables to `struct diff_options` it's easy to handle the defaults there. Signed-off-by: Patrick Steinhardt <ps@pks.im> Signed-off-by: Junio C Hamano <gitster@pobox.com>
Patrick Steinhardt committed
May 27, 2024 at 13:46 UTC
f9c19896749912da7add7ef855ea0543cca91bef
1 file changed
+10
-8
diff.c
+10
-8
@@ -62,8 +62,8 @@ static char *diff_order_file_cfg;
62
int diff_auto_refresh_index = 1;
63
static int diff_mnemonic_prefix;
64
static int diff_no_prefix;
65
-static const char *diff_src_prefix = "a/";
66
-static const char *diff_dst_prefix = "b/";
65
+static char *diff_src_prefix;
66
+static char *diff_dst_prefix;
67
static int diff_relative;
68
static int diff_stat_name_width;
69
static int diff_stat_graph_width;
@@ -411,10 +411,12 @@ int git_diff_ui_config(const char *var, const char *value,
411
return 0;
412
}
413
if (!strcmp(var, "diff.srcprefix")) {
414
- return git_config_string(&diff_src_prefix, var, value);
414
+ FREE_AND_NULL(diff_src_prefix);
415
+ return git_config_string((const char **) &diff_src_prefix, var, value);
416
}
417
if (!strcmp(var, "diff.dstprefix")) {
417
- return git_config_string(&diff_dst_prefix, var, value);
418
+ FREE_AND_NULL(diff_dst_prefix);
419
+ return git_config_string((const char **) &diff_dst_prefix, var, value);
420
}
421
if (!strcmp(var, "diff.relative")) {
422
diff_relative = git_config_bool(var, value);
@@ -3433,8 +3435,8 @@ void diff_set_noprefix(struct diff_options *options)
3435
3436
void diff_set_default_prefix(struct diff_options *options)
3437
{
3436
- options->a_prefix = diff_src_prefix;
3437
- options->b_prefix = diff_dst_prefix;
3438
+ options->a_prefix = diff_src_prefix ? diff_src_prefix : "a/";
3439
+ options->b_prefix = diff_dst_prefix ? diff_dst_prefix : "b/";
3440
}
3441
3442
struct userdiff_driver *get_textconv(struct repository *r,
@@ -5371,8 +5373,8 @@ static int diff_opt_default_prefix(const struct option *opt,
5373
5374
BUG_ON_OPT_NEG(unset);
5375
BUG_ON_OPT_ARG(optarg);
5374
- diff_src_prefix = "a/";
5375
- diff_dst_prefix = "b/";
5376
+ FREE_AND_NULL(diff_src_prefix);
5377
+ FREE_AND_NULL(diff_dst_prefix);
5378
diff_set_default_prefix(options);
5379
return 0;
5380
}