From 412dc1487390f6fde342a68e025453b3f9c6b5c6 Mon Sep 17 00:00:00 2001 From: Florian Pritz Date: Tue, 19 Apr 2011 19:19:06 +0200 Subject: fix segfault in format_bytes 0 or very big values can cause unwanted behavior so fall back to the highest suffix for big ones or to bytes for small ones. Signed-off-by: Florian Pritz --- fb-upload.c.in | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/fb-upload.c.in b/fb-upload.c.in index ff0a8ab..23fa8e0 100644 --- a/fb-upload.c.in +++ b/fb-upload.c.in @@ -22,6 +22,8 @@ #include #include +#define FORMAT_ARRAY_SIZE 5 + /* struct which holds the persistent data for progress_callback */ struct progressData { struct timeval starttime; @@ -62,11 +64,20 @@ int load_file(const char *fn, char **data, size_t *data_size) void format_bytes(double bytes, char *buf) { double base = 0; - char suffix[][4] = {"B", "KiB", "MiB", "GiB", "TiB"}; + int suffix_pos = 0; + char suffix[FORMAT_ARRAY_SIZE][4] = {"B", "KiB", "MiB", "GiB", "TiB"}; base = log(bytes) / log(1024); + suffix_pos = (int)floor(base); + + if (suffix_pos >= FORMAT_ARRAY_SIZE) + suffix_pos = FORMAT_ARRAY_SIZE-1; - snprintf(buf, 64, "%.2f%s", pow(1024, base - floor(base)), suffix[(int)floor(base)]); + if (suffix_pos > 0) { + snprintf(buf, 64, "%.2f%s", pow(1024, base - suffix_pos), suffix[suffix_pos]); + } else { + snprintf(buf, 64, "%.2fB", bytes); + } } int progress_callback(void *cb_data, -- cgit v1.2.3-24-g4f1b