* snprintf.c (snprintf): memcpy LEN bytes, not SIZE - 1, when
[gnulib.git] / lib / snprintf.c
1 /* Formatted output to strings.
2    Copyright (C) 2004, 2006 Free Software Foundation, Inc.
3    Written by Simon Josefsson and Paul Eggert.
4
5    This program is free software; you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation; either version 2, or (at your option)
8    any later version.
9
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14
15    You should have received a copy of the GNU General Public License along
16    with this program; if not, write to the Free Software Foundation,
17    Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
18
19 #ifdef HAVE_CONFIG_H
20 # include <config.h>
21 #endif
22
23 #include "snprintf.h"
24
25 #include <errno.h>
26 #include <limits.h>
27 #include <stdarg.h>
28 #include <stdlib.h>
29 #include <string.h>
30
31 #include "vasnprintf.h"
32
33 /* Some systems, like OSF/1 4.0 and Woe32, don't have EOVERFLOW.  */
34 #ifndef EOVERFLOW
35 # define EOVERFLOW E2BIG
36 #endif
37
38 /* Print formatted output to string STR.  Similar to sprintf, but
39    additional length SIZE limit how much is written into STR.  Returns
40    string length of formatted string (which may be larger than SIZE).
41    STR may be NULL, in which case nothing will be written.  On error,
42    return a negative value. */
43 int
44 snprintf (char *str, size_t size, const char *format, ...)
45 {
46   char *output;
47   size_t len;
48   size_t lenbuf = size;
49   va_list args;
50
51   va_start (args, format);
52   output = vasnprintf (str, &len, format, args);
53   len = lenbuf;
54   va_end (args);
55
56   if (!output)
57     return -1;
58
59   if (output != str)
60     {
61       if (size)
62         {
63           size_t pruned_len = (len < size ? len : size - 1);
64           memcpy (str, output, pruned_len);
65           str[pruned_len] = '\0';
66         }
67
68       free (output);
69     }
70
71   if (INT_MAX < len)
72     {
73       errno = EOVERFLOW;
74       return -1;
75     }
76
77   return len;
78 }