logo

utils-std

Collection of commonly available Unix tools
commit: 1523b277a5e4a7fc9fa8e10dbce03f6275de141f
parent b56dca2db3725933e22927c1cb18a97828f1174b
Author: Haelwenn (lanodan) Monnier <contact@hacktivis.me>
Date:   Sun, 14 Apr 2024 02:49:34 +0200

cmd/df: Use calloc instead of VLAs

Diffstat:

Mcmd/df.c36++++++++++++++++++++++++++++++++----
1 file changed, 32 insertions(+), 4 deletions(-)

diff --git a/cmd/df.c b/cmd/df.c @@ -7,6 +7,7 @@ #include "../lib/humanize.h" +#include <assert.h> #include <ctype.h> // iscntrl, isspace #include <errno.h> // errno #include <mntent.h> @@ -106,16 +107,33 @@ main(int argc, char *argv[]) bool tty_out = isatty(1); int col_width = tty_out ? 10 : 0; - if(!tty_out) fs_col_width = 0; + if(!tty_out) + { + errno = 0; + fs_col_width = 0; + } + + dev_t *arg_devs = NULL; + + if(argc > 0) + { + arg_devs = calloc(argc, sizeof(dev_t)); + if(arg_devs == NULL) + { + fprintf(stderr, "df: Failed to allocate arg_devs array: %s\n", strerror(errno)); + return 1; + } + } + + assert(errno == 0); - dev_t arg_devs[argc]; for(int i = 0; i < argc; i++) { struct stat file_stats; if(stat(argv[i], &file_stats) != 0) { fprintf(stderr, "df: Error stat(\"%s\", _): %s\n", argv[i], strerror(errno)); - return 1; + goto error; } arg_devs[i] = file_stats.st_dev; @@ -141,11 +159,12 @@ main(int argc, char *argv[]) // End: Print header + assert(errno == 0); FILE *mounted = setmntent(MOUNTED, "r"); if(mounted == NULL) { fprintf(stderr, "df: Error opening setmntent(\"" MOUNTED "\", \"r\"): %s", strerror(errno)); - return 1; + goto error; } // FIXME: Fix maximum number of mount entries / devices @@ -200,6 +219,7 @@ main(int argc, char *argv[]) if(remote) continue; } + assert(errno == 0); struct stat file_stats; if(!opt_a || argc > 0) { @@ -244,6 +264,7 @@ main(int argc, char *argv[]) // Note: musl prior to 1.2.5 has broken getmntent when octal sequences and carriage return is used // https://git.musl-libc.org/cgit/musl/commit/src/misc/mntent.c?id=f314e133929b6379eccc632bef32eaebb66a7335 // https://git.musl-libc.org/cgit/musl/commit/src/misc/mntent.c?id=ee1d39bc1573c1ae49ee6b658938b56bbef95a6c + assert(errno == 0); struct statvfs stats; if(statvfs(mntent->mnt_dir, &stats) != 0) { @@ -323,5 +344,12 @@ main(int argc, char *argv[]) endmntent(mounted); + if(argc > 0) free(arg_devs); + return 0; + +error: + if(argc > 0) free(arg_devs); + + return 1; }