From cb518ecd55cd7a45d0368fb9d68a1981c6c91adf Mon Sep 17 00:00:00 2001 From: dzwdz Date: Sun, 5 May 2024 14:58:44 +0200 Subject: libc: implement asprintf --- src/cmd/ps.c | 23 +++++++++++------------ 1 file changed, 11 insertions(+), 12 deletions(-) (limited to 'src/cmd/ps.c') diff --git a/src/cmd/ps.c b/src/cmd/ps.c index c855251..98aab8a 100644 --- a/src/cmd/ps.c +++ b/src/cmd/ps.c @@ -19,7 +19,6 @@ main(int argc, const char *argv[]) const char *path = argc >= 2 ? argv[1] : "/proc/"; if (argc > 2) usage(); - char *procbuf = malloc(4096); DIR *dir = opendir(path); if (!dir) { err(1, "couldn't open %s", path); @@ -28,27 +27,27 @@ main(int argc, const char *argv[]) struct dirent *de; while ((de = readdir(dir))) { const char *name = de->d_name; - if (isdigit(name[0])) { - FILE *g; - sprintf(procbuf, "%s%smem", path, name); - g = fopen(procbuf, "r"); + char psdata[128]; + char *s; + if (isdigit(name[0]) && asprintf(&s, "%s%smem", path, name) >= 0) { + FILE *g = fopen(s, "r"); + free(s); if (!g) { - warn("couldn't open \"%s\"", procbuf); - strcpy(procbuf, "(can't peek)"); + warn("couldn't open \"%s\"", s); + strcpy(psdata, "(can't peek)"); } else { fseek(g, (long)&_psdata_loc->desc, SEEK_SET); - if (fread(procbuf, 1, 128, g) <= 0) { - strcpy(procbuf, "(no psdata)"); + if (fread(psdata, 1, sizeof(psdata)-1, g) <= 0) { + strcpy(psdata, "(no psdata)"); } - procbuf[128] = '\0'; + psdata[sizeof(psdata)-1] = '\0'; fclose(g); } *strchr(name, '/') = '\0'; - printf("%s\t%s\n", name, procbuf); + printf("%s\t%s\n", name, psdata); } } - free(procbuf); closedir(dir); return 0; } -- cgit v1.2.3