diff options
author | Bruno Haible <bruno@clisp.org> | 2004-10-07 16:15:22 +0000 |
---|---|---|
committer | Bruno Haible <bruno@clisp.org> | 2004-10-07 16:15:22 +0000 |
commit | f5200a50fa42fdaed40ecc67b27f41be328a6a01 (patch) | |
tree | e5210de2a546aef174a23e1aedede165eb75a0df | |
parent | 68126b9700a6cefbfe0f578fa7dbe71829c52e8f (diff) | |
download | gnulib-f5200a50fa42fdaed40ecc67b27f41be328a6a01.tar.gz |
Avoid a memory allocation when possible.
-rw-r--r-- | lib/ChangeLog | 5 | ||||
-rw-r--r-- | lib/snprintf.c | 12 |
2 files changed, 11 insertions, 6 deletions
diff --git a/lib/ChangeLog b/lib/ChangeLog index 1c3510dbdf..08659a34df 100644 --- a/lib/ChangeLog +++ b/lib/ChangeLog @@ -1,3 +1,8 @@ +2004-10-07 Bruno Haible <bruno@clisp.org> + + * snprintf.c (snprintf): Avoid a memory allocation if the result fits + into the provided buffer. + 2004-10-06 Paul Eggert <eggert@cs.ucla.edu> * diacrit.c, diacrit.h: Add GPL notice. diff --git a/lib/snprintf.c b/lib/snprintf.c index 667ed94625..9a4edc1f5f 100644 --- a/lib/snprintf.c +++ b/lib/snprintf.c @@ -42,19 +42,19 @@ snprintf (char *str, size_t size, const char *format, ...) va_list args; va_start (args, format); - output = vasnprintf (NULL, &len, format, args); + len = size; + output = vasnprintf (str, &len, format, args); va_end (args); if (!output) return -1; - if (str && size > 0) - { - memcpy (str, output, MIN (len + 1, size)); + if (str != NULL) + if (len > size - 1) /* equivalent to: (size > 0 && len >= size) */ str[size - 1] = '\0'; - } - free (output); + if (output != str) + free (output); return len; } |