diff mbox series

[1/2] checkout: handling branch_info memory leak

Message ID e9f6be692db40978b835e7298c1a1c664566ec84.1639117329.git.gitgitgadget@gmail.com (mailing list archive)
State New, archived
Headers show
Series checkout: introduce "--to-branch" option | expand

Commit Message

ZheNing Hu Dec. 10, 2021, 6:22 a.m. UTC
From: ZheNing Hu <adlternative@gmail.com>

On the checkout code path, we dynamically allocate
memory for `refname` and `path` in `struct branch_info`,
but did not free their memory at the end. So introduce
branch_info_clear() which can free branch_info memory.

Signed-off-by: ZheNing Hu <adlternative@gmail.com>
---
 builtin/checkout.c | 16 ++++++++++++++--
 1 file changed, 14 insertions(+), 2 deletions(-)

Comments

Ævar Arnfjörð Bjarmason Dec. 10, 2021, 7:13 a.m. UTC | #1
On Fri, Dec 10 2021, ZheNing Hu via GitGitGadget wrote:

> From: ZheNing Hu <adlternative@gmail.com>
>
> On the checkout code path, we dynamically allocate
> memory for `refname` and `path` in `struct branch_info`,
> but did not free their memory at the end. So introduce
> branch_info_clear() which can free branch_info memory.

This (partially) duplicates my 9081a421a6d (checkout: fix "branch info"
memory leaks, 2021-11-16) which is in "next" already.
diff mbox series

Patch

diff --git a/builtin/checkout.c b/builtin/checkout.c
index cbf73b8c9f6..3eeac3147f2 100644
--- a/builtin/checkout.c
+++ b/builtin/checkout.c
@@ -103,6 +103,15 @@  struct branch_info {
 	char *checkout;
 };
 
+static void branch_info_clear(struct branch_info *branch_info) {
+	if (branch_info->path) {
+		free((char *)branch_info->path);
+		branch_info->path = NULL;
+	}
+	if (branch_info->refname)
+		FREE_AND_NULL(branch_info->refname);
+}
+
 static int post_checkout_hook(struct commit *old_commit, struct commit *new_commit,
 			      int changed)
 {
@@ -1578,6 +1587,7 @@  static int checkout_main(int argc, const char **argv, const char *prefix,
 {
 	struct branch_info new_branch_info;
 	int parseopt_flags = 0;
+	int ret = 0;
 
 	memset(&new_branch_info, 0, sizeof(new_branch_info));
 	opts->overwrite_ignore = 1;
@@ -1768,9 +1778,11 @@  static int checkout_main(int argc, const char **argv, const char *prefix,
 
 	UNLEAK(opts);
 	if (opts->patch_mode || opts->pathspec.nr)
-		return checkout_paths(opts, &new_branch_info);
+		ret = checkout_paths(opts, &new_branch_info);
 	else
-		return checkout_branch(opts, &new_branch_info);
+		ret = checkout_branch(opts, &new_branch_info);
+	branch_info_clear(&new_branch_info);
+	return ret;
 }
 
 int cmd_checkout(int argc, const char **argv, const char *prefix)