On Sat, Apr 06, 2024 at 09:50:23PM -0400, Eric Sunshine wrote: > On Sat, Apr 6, 2024 at 9:00 PM Jeff King <peff@xxxxxxxx> wrote: > > 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@xxxxxxxx> > > --- > > 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? That's nothing new with my patch, though, is it? The same would apply for git_config_pathname(). And git_config_string() for that matter. I'm also struggling to imagine what it _would_ copy into "v" on failure anyway. -Peff