git-config: fix regexp memory leaks on error conditions
The get_value function has a goto label for cleaning up on errors, but it only cleans up half of what the function might allocate. Let's also clean up the key and regexp variables there. Note that we need to take special care when compiling the regex fails to clean it up ourselves, since it is in a half-constructed state (we would want to free it, but not regfree it). Similarly, we fix git_config_parse_key to return NULL when it fails, not a pointer to some already-freed memory. Signed-off-by: Jeff King <peff@peff.net>
Jeff King committed
Oct 23, 2012 at 15:40 UTC
97ed50f93ba592b50278a8161282e862cb87b4c0
2 files changed
+14
-10
builtin/config.c
+13
-10
@@ -195,7 +195,8 @@ static int get_value(const char *key_, const char *regex_)
195
key_regexp = (regex_t*)xmalloc(sizeof(regex_t));
196
if (regcomp(key_regexp, key, REG_EXTENDED)) {
197
fprintf(stderr, "Invalid key pattern: %s\n", key_);
198
- free(key);
198
+ free(key_regexp);
199
+ key_regexp = NULL;
200
ret = CONFIG_INVALID_PATTERN;
201
goto free_strings;
202
}
@@ -215,6 +216,8 @@ static int get_value(const char *key_, const char *regex_)
216
regexp = (regex_t*)xmalloc(sizeof(regex_t));
217
if (regcomp(regexp, regex_, REG_EXTENDED)) {
218
fprintf(stderr, "Invalid pattern: %s\n", regex_);
219
+ free(regexp);
220
+ regexp = NULL;
221
ret = CONFIG_INVALID_PATTERN;
222
goto free_strings;
223
}
@@ -247,6 +250,15 @@ static int get_value(const char *key_, const char *regex_)
250
if (!do_all && !seen && system_wide)
251
git_config_from_file(fn, system_wide, data);
252
253
+ if (do_all)
254
+ ret = !seen;
255
+ else
256
+ ret = (seen == 1) ? 0 : seen > 1 ? 2 : 1;
257
+
258
+free_strings:
259
+ free(repo_config);
260
+ free(global);
261
+ free(xdg);
262
free(key);
263
if (key_regexp) {
264
regfree(key_regexp);
@@ -257,15 +269,6 @@ static int get_value(const char *key_, const char *regex_)
269
free(regexp);
270
}
271
260
- if (do_all)
261
- ret = !seen;
262
- else
263
- ret = (seen == 1) ? 0 : seen > 1 ? 2 : 1;
264
-
265
-free_strings:
266
- free(repo_config);
267
- free(global);
268
- free(xdg);
272
return ret;
273
}
274
config.c
+1
@@ -1280,6 +1280,7 @@ int git_config_parse_key(const char *key, char **store_key, int *baselen_)
1280
1281
out_free_ret_1:
1282
free(*store_key);
1283
+ *store_key = NULL;
1284
return -CONFIG_INVALID_KEY;
1285
}
1286