# [PATCH] update-index: fix xgetcwd() related memory leak

2 messages from 2017-03-30 to 2017-03-30. Participants: Christian Couder, Jeff King.
Thread: https://gitlist.dev/t/45545

## Christian Couder, 2017-03-30 06:22

Subject: [PATCH] update-index: fix xgetcwd() related memory leak
Message-ID: <20170330062208.29018-1-chriscool@tuxfamily.org>
URL: https://gitlist.dev/e/20170330062208.29018-1-chriscool%40tuxfamily.org

```
As xgetcwd() returns an allocated buffer, we should free this
buffer when we don't need it any more.

This was found by Coverity.

Reported-by: Jeff King <peff@peff.net>
Signed-off-by: Christian Couder <chriscool@tuxfamily.org>
---
 builtin/update-index.c | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)

diff --git a/builtin/update-index.c b/builtin/update-index.c
index d74d72cc7f..ebfc09faa0 100644
--- a/builtin/update-index.c
+++ b/builtin/update-index.c
@@ -125,12 +125,16 @@ static int test_if_untracked_cache_is_supported(void)
 	struct stat st;
 	struct stat_data base;
 	int fd, ret = 0;
+	char *cwd;
 
 	strbuf_addstr(&mtime_dir, "mtime-test-XXXXXX");
 	if (!mkdtemp(mtime_dir.buf))
 		die_errno("Could not make temporary directory");
 
-	fprintf(stderr, _("Testing mtime in '%s' "), xgetcwd());
+	cwd = xgetcwd();
+	fprintf(stderr, _("Testing mtime in '%s' "), cwd);
+	free(cwd);
+
 	atexit(remove_test_directory);
 	xstat_mtime_dir(&st);
 	fill_stat_data(&base, &st);
-- 
2.12.2.510.ge1104a5ee5.dirty


```

## Jeff King, 2017-03-30 06:23

Subject: Re: [PATCH] update-index: fix xgetcwd() related memory leak
Message-ID: <20170330062337.rwd2u5k7s57zczuo@sigill.intra.peff.net>
URL: https://gitlist.dev/e/20170330062337.rwd2u5k7s57zczuo%40sigill.intra.peff.net
In-Reply-To: <20170330062208.29018-1-chriscool@tuxfamily.org>

```
On Thu, Mar 30, 2017 at 08:22:08AM +0200, Christian Couder wrote:

> As xgetcwd() returns an allocated buffer, we should free this
> buffer when we don't need it any more.
> 
> This was found by Coverity.
> 
> Reported-by: Jeff King <peff@peff.net>
> Signed-off-by: Christian Couder <chriscool@tuxfamily.org>
> ---
>  builtin/update-index.c | 6 +++++-
>  1 file changed, 5 insertions(+), 1 deletion(-)
> 
> diff --git a/builtin/update-index.c b/builtin/update-index.c
> index d74d72cc7f..ebfc09faa0 100644
> --- a/builtin/update-index.c
> +++ b/builtin/update-index.c
> @@ -125,12 +125,16 @@ static int test_if_untracked_cache_is_supported(void)
>  	struct stat st;
>  	struct stat_data base;
>  	int fd, ret = 0;
> +	char *cwd;
>  
>  	strbuf_addstr(&mtime_dir, "mtime-test-XXXXXX");
>  	if (!mkdtemp(mtime_dir.buf))
>  		die_errno("Could not make temporary directory");
>  
> -	fprintf(stderr, _("Testing mtime in '%s' "), xgetcwd());
> +	cwd = xgetcwd();
> +	fprintf(stderr, _("Testing mtime in '%s' "), cwd);
> +	free(cwd);
> +

Yep, this solution looks obviously correct to me.

-Peff

```
