Commit 1725ce0a3db295a68aa6ec066e8e3baf64c6eb2c

Edward Thomson 2019-09-11T09:37:24

Merge pull request #5224 from lrm29/check_if_repository_memory_leak open:fix memory leak when passing NULL to git_repository_open_ext

diff --git a/src/repository.c b/src/repository.c
index f9c4ef4..2cb59e0 100644
--- a/src/repository.c
+++ b/src/repository.c
@@ -800,7 +800,7 @@ int git_repository_open_ext(
 	unsigned is_worktree;
 	git_buf gitdir = GIT_BUF_INIT, workdir = GIT_BUF_INIT,
 		gitlink = GIT_BUF_INIT, commondir = GIT_BUF_INIT;
-	git_repository *repo;
+	git_repository *repo = NULL;
 	git_config *config = NULL;
 
 	if (flags & GIT_REPOSITORY_OPEN_FROM_ENV)
@@ -813,7 +813,7 @@ int git_repository_open_ext(
 		&gitdir, &workdir, &gitlink, &commondir, start_path, flags, ceiling_dirs);
 
 	if (error < 0 || !repo_ptr)
-		return error;
+		goto cleanup;
 
 	repo = repository_alloc();
 	GIT_ERROR_CHECK_ALLOC(repo);
@@ -859,11 +859,14 @@ int git_repository_open_ext(
 cleanup:
 	git_buf_dispose(&gitdir);
 	git_buf_dispose(&workdir);
+	git_buf_dispose(&gitlink);
+	git_buf_dispose(&commondir);
 	git_config_free(config);
 
 	if (error < 0)
 		git_repository_free(repo);
-	else
+
+	if (repo_ptr)
 		*repo_ptr = repo;
 
 	return error;
diff --git a/tests/repo/open.c b/tests/repo/open.c
index edcf93f..83b53c4 100644
--- a/tests/repo/open.c
+++ b/tests/repo/open.c
@@ -88,6 +88,17 @@ void test_repo_open__open_with_discover(void)
 	cl_fixture_cleanup("attr");
 }
 
+void test_repo_open__check_if_repository(void)
+{
+	cl_git_sandbox_init("empty_standard_repo");
+
+	/* Pass NULL for the output parameter to check for but not open the repo */
+	cl_git_pass(git_repository_open_ext(NULL, "empty_standard_repo", 0, NULL));
+	cl_git_fail(git_repository_open_ext(NULL, "repo_does_not_exist", 0, NULL));
+
+	cl_fixture_cleanup("empty_standard_repo");
+}
+
 static void make_gitlink_dir(const char *dir, const char *linktext)
 {
 	git_buf path = GIT_BUF_INIT;