Subject: Re: [PATCH 1/4] branch: add branch_checked_out() helper

From: Junio C Hamano <[email-masked]>
Date: Thu, 09 Jun 2022 16:47:48 -0700

"Derrick Stolee via GitGitGadget" <[email-masked]> writes:

> +static void prepare_checked_out_branches(void)
> +{
> +	int i = 0;
> +	struct worktree **worktrees;
> +
> +	if (initialized_checked_out_branches)
> +		return;
> +	initialized_checked_out_branches = 1;
> +
> +	worktrees = get_worktrees();
> +
> +	while (worktrees[i]) {
> +		struct worktree *wt = worktrees[i++];
> +
> +		if (wt->is_bare)
> +			continue;
> +
> +		if (wt->head_ref)
> +			strmap_put(&current_checked_out_branches,
> +				   wt->head_ref,
> +				   xstrdup(wt->path));
> +	}

If two worktrees have by accident or by bug checked out the same
branch, this strmap_put() will leak, as it overwrites the path to
the worktree we found earlier with the branch checked out with the
path to the worktree we just discovered with the same branch checked
out.  We could easily work it around by immediately freeing what
comes back from strmap_put(), presumably.  The resulting code

		if (wt->head_ref)
			free(strmap_put(...));

may look strange, though, especially because we will see more
instances of strmap_put() in this loop in later steps.