commit: e715848e1690e4dcce087ee12f9e8a4de9d1a961
parent 1a1008c3e415b99f191a977c2a01d1ac9eaf1295
Author: Haelwenn (lanodan) Monnier <contact@hacktivis.me>
Date: Thu, 24 Jul 2025 20:30:59 +0200
cmd/paste: fix fopen & mem leaks detected by gcc analyzer
Diffstat:
M | cmd/paste.c | 42 | +++++++++++++++++++++++++++++++++++++++--- |
1 file changed, 39 insertions(+), 3 deletions(-)
diff --git a/cmd/paste.c b/cmd/paste.c
@@ -37,6 +37,7 @@
#include "../libutils/err.h"
#include "../libutils/getopt_nolong.h"
+#include <assert.h>
#include <errno.h>
#include <limits.h>
#include <locale.h>
@@ -73,14 +74,19 @@ parallel(char **argv)
char *p;
LIST *head, *tmp;
int opencnt, output;
+ int err = 0;
for(cnt = 0, head = tmp = NULL; (p = *argv); ++argv, ++cnt)
{
if((lp = malloc(sizeof(LIST))) == NULL) utils_err(1, NULL);
if(p[0] == '-' && !p[1])
lp->fp = stdin;
- else if(!(lp->fp = fopen(p, "r")))
- utils_err(1, "%s", p);
+ else
+ {
+ lp->fp = fopen(p, "r");
+ if(!lp->fp) utils_err(1, "%s", p);
+ assert(lp->fp != stdin);
+ }
lp->next = NULL;
lp->cnt = cnt;
lp->name = p;
@@ -105,6 +111,18 @@ parallel(char **argv)
if((ich = getwc(lp->fp)) == WEOF)
{
if(!--opencnt) break;
+ if(lp->fp && lp->fp != stdin)
+ {
+ if(fclose(lp->fp) != 0)
+ {
+ fprintf(stderr,
+ "%s: error: Failed closing file '%s': %s\n",
+ argv0,
+ lp->name,
+ strerror(errno));
+ err = 1;
+ }
+ }
lp->fp = NULL;
if(output && lp->cnt && (ch = delim[(lp->cnt - 1) % delimcnt])) putwchar(ch);
continue;
@@ -121,7 +139,9 @@ parallel(char **argv)
}
else if((ch = delim[(lp->cnt - 1) % delimcnt]))
putwchar(ch);
+
if(ich == linedelim) continue;
+
do
{
putwchar(ich);
@@ -130,7 +150,23 @@ parallel(char **argv)
if(output) putwchar(linedelim);
}
- return (0);
+ for(lp = head; lp;)
+ {
+ if(lp->fp && lp->fp != stdin)
+ {
+ if(fclose(lp->fp) != 0)
+ {
+ fprintf(
+ stderr, "%s: error: Failed closing file '%s': %s\n", argv0, lp->name, strerror(errno));
+ err = 1;
+ }
+ }
+ LIST *next = lp->next;
+ free(lp);
+ lp = next;
+ }
+
+ return err;
}
static int