From a67431b09b023ddeb687fb37f83939d28b34af5a Mon Sep 17 00:00:00 2001 From: kientzle Date: Tue, 13 Apr 2004 23:49:02 +0000 Subject: 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. --- usr.bin/tar/util.c | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) (limited to 'usr.bin') 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 -- cgit v1.1