Skip to content

Commit f332069

Browse files
peffgitster
authored andcommitted
walker_fetch: fix minor memory leak
We sometimes allocate "msg" on the heap, but will fail to free it if we hit the failure code path. We can instead keep a separate variable that is safe to be freed no matter how we get to the failure code path. While we're here, we can also do two readability improvements: 1. Use xstrfmt instead of a manual malloc/sprintf 2. Due to the "maybe we allocate msg, maybe we don't" strategy, the logic for deciding which message to show was split into two parts. Since the deallocation is now pushed onto a separate variable, this is no longer a concern, and we can keep all of the logic in the same place. Signed-off-by: Jeff King <[email protected]> Signed-off-by: Junio C Hamano <[email protected]>
1 parent 5c1753b commit f332069

File tree

1 file changed

+9
-9
lines changed

1 file changed

+9
-9
lines changed

walker.c

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -253,7 +253,8 @@ int walker_fetch(struct walker *walker, int targets, char **target,
253253
{
254254
struct ref_lock **lock = xcalloc(targets, sizeof(struct ref_lock *));
255255
unsigned char *sha1 = xmalloc(targets * 20);
256-
char *msg;
256+
const char *msg;
257+
char *to_free = NULL;
257258
int ret;
258259
int i;
259260

@@ -285,28 +286,27 @@ int walker_fetch(struct walker *walker, int targets, char **target,
285286
if (loop(walker))
286287
goto unlock_and_fail;
287288

288-
if (write_ref_log_details) {
289-
msg = xmalloc(strlen(write_ref_log_details) + 12);
290-
sprintf(msg, "fetch from %s", write_ref_log_details);
291-
} else {
292-
msg = NULL;
293-
}
289+
if (write_ref_log_details)
290+
msg = to_free = xstrfmt("fetch from %s", write_ref_log_details);
291+
else
292+
msg = "fetch (unknown)";
294293
for (i = 0; i < targets; i++) {
295294
if (!write_ref || !write_ref[i])
296295
continue;
297-
ret = write_ref_sha1(lock[i], &sha1[20 * i], msg ? msg : "fetch (unknown)");
296+
ret = write_ref_sha1(lock[i], &sha1[20 * i], msg);
298297
lock[i] = NULL;
299298
if (ret)
300299
goto unlock_and_fail;
301300
}
302-
free(msg);
301+
free(to_free);
303302

304303
return 0;
305304

306305
unlock_and_fail:
307306
for (i = 0; i < targets; i++)
308307
if (lock[i])
309308
unlock_ref(lock[i]);
309+
free(to_free);
310310

311311
return -1;
312312
}

0 commit comments

Comments
 (0)