indent(1): Fix memory leaks pointed out by clang-analyzer.

Shift the responsibility of allocating memory for the string duplicate
from the caller (set_option, add_typedefs_from_file) to the callee
(add_typename) as it has more knowledge about when the duplication
actually needs to occur.

Taken from:	Piotr Stefaniak
This commit is contained in:
Pedro F. Giffuni 2016-08-23 01:40:45 +00:00
parent 728af0b7fc
commit f3c23ec321
Notes: svn2git 2020-12-20 02:59:44 +00:00
svn path=/head/; revision=304650
2 changed files with 11 additions and 15 deletions

View File

@ -294,12 +294,7 @@ set_option(char *arg)
case KEY:
if (*param_start == 0)
goto need_param;
{
char *str = strdup(param_start);
if (str == NULL)
err(1, NULL);
add_typename(str);
}
add_typename(param_start);
break;
case KEY_FILE:
@ -342,7 +337,6 @@ add_typedefs_from_file(const char *str)
{
FILE *file;
char line[BUFSIZ];
char *copy;
if ((file = fopen(str, "r")) == NULL) {
fprintf(stderr, "indent: cannot open file %s\n", str);
@ -351,10 +345,7 @@ add_typedefs_from_file(const char *str)
while ((fgets(line, BUFSIZ, file)) != NULL) {
/* Remove trailing whitespace */
line[strcspn(line, " \t\n\r")] = '\0';
if ((copy = strdup(line)) == NULL) {
err(1, NULL);
}
add_typename(copy);
add_typename(line);
}
fclose(file);
}

View File

@ -594,6 +594,7 @@ void
add_typename(const char *key)
{
int comparison;
const char *copy;
if (typename_top + 1 >= typename_count) {
typenames = realloc((void *)typenames,
@ -602,11 +603,12 @@ add_typename(const char *key)
err(1, NULL);
}
if (typename_top == -1)
typenames[++typename_top] = key;
typenames[++typename_top] = copy = strdup(key);
else if ((comparison = strcmp(key, typenames[typename_top])) >= 0) {
/* take advantage of sorted input */
if (comparison != 0) /* remove duplicates */
typenames[++typename_top] = key;
if (comparison == 0) /* remove duplicates */
return;
typenames[++typename_top] = copy = strdup(key);
}
else {
int p;
@ -617,6 +619,9 @@ add_typename(const char *key)
return;
memmove(&typenames[p + 1], &typenames[p],
sizeof(typenames[0]) * (++typename_top - p));
typenames[p] = key;
typenames[p] = copy = strdup(key);
}
if (copy == NULL)
err(1, NULL);
}