New module 'memmem', from Simon Josefsson.
[gnulib.git] / lib / snprintf.c
index 6cc44aa..667ed94 100644 (file)
 # include <config.h>
 #endif
 
-/* Get specification.  */
 #include "snprintf.h"
 
-/* Get vasnprintf.  */
-#include "vasnprintf.h"
+#include <stdarg.h>
+#include <stdlib.h>
+#include <string.h>
 
-/* Get MIN. */
-#include <minmax.h>
+#include "minmax.h"
+#include "vasnprintf.h"
 
 /* Print formatted output to string STR.  Similar to sprintf, but
    additional length SIZE limit how much is written into STR.  Returns
 int
 snprintf (char *str, size_t size, const char *format, ...)
 {
+  char *output;
   size_t len;
-  char *out = vasnprintf (NULL, &len, format, args);
+  va_list args;
+
+  va_start (args, format);
+  output = vasnprintf (NULL, &len, format, args);
+  va_end (args);
 
-  if (!out)
+  if (!output)
     return -1;
 
-  if (str)
+  if (str && size > 0)
     {
-      memcpy (str, out, MIN (len + 1, size));
+      memcpy (str, output, MIN (len + 1, size));
       str[size - 1] = '\0';
     }
 
-  free (out);
+  free (output);
 
   return len;
 }