Re: [PATCH 03/11] config: prefer git_config_string_dup() for temp variables
- From
Eric Sunshine <sunshine@sunshineco.com>
- Date
- Apr 7, 2024, 01:50 UTC
- Message-ID
- <CAPig+cRyya=hUYtdzoqgFLQq0eEnkgH1ayZTLBGtM2gRrc2yTw@mail.gmail.com>
- In-Reply-To
- <20240407010037.GC868358@coredump.intra.peff.net>
On Sat, Apr 6, 2024 at 9:00 PM Jeff King <peff@peff.net> wrote:
Show 23 quoted lines
> In some cases we may use git_config_string() or git_config_pathname() to > read a value into a temporary variable, and then either hand off memory > ownership of the new variable or free it. These are not potential leaks, > since we know that there is no previous value we are overwriting. > > However, it's worth converting these to use git_config_string_dup() and > git_config_pathname_dup(). It makes it easier to audit for leaky cases, > and possibly we can get rid of the leak-prone functions in the future. > Plus it lets the const-ness of our variables match their expected memory > ownership, which avoids some casts when calling free(). > > Signed-off-by: Jeff King <peff@peff.net> > --- > diff --git a/builtin/config.c b/builtin/config.c > @@ -282,11 +282,11 @@ static int format_config(struct strbuf *buf, const char *key_, > - const char *v; > - if (git_config_pathname(&v, key_, value_) < 0) > + char *v = NULL; > + if (git_config_pathname_dup(&v, key_, value_) < 0) > return -1; > strbuf_addstr(buf, v); > - free((char *)v); > + free(v);
This revised code implies that git_config_pathname_dup() doesn't assign allocated memory to `v` in the "failure" case, thus it is safe to `return` immediately without calling free(v). However, the documentation for git_config_pathname_dup() and cousins doesn't state this explicitly, which means the caller needs to peek into the implementation of git_config_pathname_dup() to verify that it is safe to write code such as the above. Hence, should the documentation be updated to explain that `v` won't be modified in the "failure" case?