diff options
author | kientzle <kientzle@FreeBSD.org> | 2004-04-13 23:49:02 +0000 |
---|---|---|
committer | kientzle <kientzle@FreeBSD.org> | 2004-04-13 23:49:02 +0000 |
commit | a67431b09b023ddeb687fb37f83939d28b34af5a (patch) | |
tree | 5dbcbc43c3eb1b9aaf504fdb2d5012f9ed817369 | |
parent | 5c2c79eafdaffd172c20dd2cebc96f3dea266b96 (diff) | |
download | FreeBSD-src-a67431b09b023ddeb687fb37f83939d28b34af5a.zip FreeBSD-src-a67431b09b023ddeb687fb37f83939d28b34af5a.tar.gz |
Eliminate a lot of malloc/free calls by using
a stack-allocated buffer for safe_fprintf formatting.
Only if the result is too large do we resort to malloc.
-rw-r--r-- | usr.bin/tar/util.c | 15 |
1 files changed, 11 insertions, 4 deletions
diff --git a/usr.bin/tar/util.c b/usr.bin/tar/util.c index a9ccdfc..66e356d 100644 --- a/usr.bin/tar/util.c +++ b/usr.bin/tar/util.c @@ -45,19 +45,24 @@ void safe_fprintf(FILE *f, const char *fmt, ...) { char *buff; + char *buffheap; + char buffstack[256]; int bufflength; int length; va_list ap; char *p; - bufflength = 512; - buff = malloc(bufflength); + /* Use a stack-allocated buffer if we can. */ + buffheap = NULL; + bufflength = 256; + buff = buffstack; va_start(ap, fmt); length = vsnprintf(buff, bufflength, fmt, ap); + /* If the result is too large, allocate a buffer on the heap. */ if (length >= bufflength) { bufflength = length+1; - buff = realloc(buff, bufflength); + buff = buffheap = malloc(bufflength); length = vsnprintf(buff, bufflength, fmt, ap); } va_end(ap); @@ -83,7 +88,9 @@ safe_fprintf(FILE *f, const char *fmt, ...) fprintf(f, "\\%03o", c); } } - free(buff); + /* If we allocated a heap-based buffer, free it now. */ + if (buffheap != NULL) + free(buffheap); } static void |