changeset 7121:2b481e5376f7

* snprintf.c (snprintf): memcpy LEN bytes, not SIZE - 1, when LEN is smaller than SIZE. Suggested by Bruno Haible. Also, help the compiler to keep LEN in a register.
author Paul Eggert <eggert@cs.ucla.edu>
date Fri, 11 Aug 2006 17:42:19 +0000
parents f8ce5033258e
children 334ac0e6023c
files lib/ChangeLog lib/snprintf.c
diffstat 2 files changed, 11 insertions(+), 3 deletions(-) [+]
line wrap: on
line diff
--- a/lib/ChangeLog
+++ b/lib/ChangeLog
@@ -1,3 +1,9 @@
+2006-08-11  Paul Eggert  <eggert@cs.ucla.edu>
+
+	* snprintf.c (snprintf): memcpy LEN bytes, not SIZE - 1, when
+	LEN is smaller than SIZE.  Suggested by Bruno Haible.
+	Also, help the compiler to keep LEN in a register.
+
 2006-08-10  Paul Eggert  <eggert@cs.ucla.edu>
 
 	* .cppi-disable: Add snprintf.h, socket_.h.
--- a/lib/snprintf.c
+++ b/lib/snprintf.c
@@ -45,11 +45,12 @@
 {
   char *output;
   size_t len;
+  size_t lenbuf = size;
   va_list args;
 
   va_start (args, format);
-  len = size;
   output = vasnprintf (str, &len, format, args);
+  len = lenbuf;
   va_end (args);
 
   if (!output)
@@ -59,8 +60,9 @@
     {
       if (size)
 	{
-	  memcpy (str, output, size - 1);
-	  str[size - 1] = '\0';
+	  size_t pruned_len = (len < size ? len : size - 1);
+	  memcpy (str, output, pruned_len);
+	  str[pruned_len] = '\0';
 	}
 
       free (output);