From 23fa33d7061a2bba7f0732ea0c8c324a560a65d3 Mon Sep 17 00:00:00 2001 From: Alan Coopersmith Date: Sat, 13 Aug 2022 14:39:42 -0700 Subject: Improve handling of realloc() Fixes cppcheck warning: [fslsfonts.c:268]: (error) Common realloc mistake: 'font_list' nulled but not freed upon failure Signed-off-by: Alan Coopersmith --- fslsfonts.c | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) (limited to 'fslsfonts.c') diff --git a/fslsfonts.c b/fslsfonts.c index 3138a81..3608e5a 100644 --- a/fslsfonts.c +++ b/fslsfonts.c @@ -264,17 +264,19 @@ get_list(const char *pattern) program_name, pattern); return; } - if (font_list) - font_list = realloc(font_list, (font_cnt + (unsigned) available) - * sizeof(FontList)); - else - font_list = malloc((font_cnt + (unsigned) available) - * sizeof(FontList)); - if (font_list == NULL) { - fprintf(stderr, "%s: unable to allocate %zu bytes for font list\n", - program_name, - (font_cnt + (unsigned) available) * sizeof(FontList)); - exit(-1); + else { + FontList *old_list = font_list; + + font_list = realloc(old_list, (font_cnt + (unsigned) available) + * sizeof(FontList)); + + if (font_list == NULL) { + free(old_list); + fprintf(stderr, "%s: unable to allocate %zu bytes for font list\n", + program_name, + (font_cnt + (unsigned) available) * sizeof(FontList)); + exit(-1); + } } for (i = 0; i < available; i++) { font_list[font_cnt].name = fonts[i]; -- cgit v1.2.3