Subject: Re: Query about return value of snprintf
To: None <>
From: Andreas Jaeger <>
List: tech-userlevel
Date: 06/17/1999 23:38:26
The man page in man-pages <= 1.24 document the behaviour of glibc
2.0.  The behaviour of glibc 2.1 will be documented in the next
manpages release.  In this case the netbsd man page agrees with glibc
2.1's documented behaviour.

glibc 2.1 is documented in the info pages which should tell you (the
last paragraph is new):
 - Function: int snprintf (char *S, size_t SIZE, const char *TEMPLATE,
     The `snprintf' function is similar to `sprintf', except that the
     SIZE argument specifies the maximum number of characters to
     produce.  The trailing null character is counted towards this
     limit, so you should allocate at least SIZE characters for the
     string S.

     The return value is the number of characters which would be
     generated for the given input, excluding the trailing null.  If
     this value is greater or equal to SIZE, not all characters from
     the result have been stored in S.  You should try again with a
     bigger output string.  Here is an example of doing this:

          /* Construct a message describing the value of a variable
             whose name is NAME and whose value is VALUE. */
          char *
          make_message (char *name, char *value)
            /* Guess we need no more than 100 chars of space. */
            int size = 100;
            char *buffer = (char *) xmalloc (size);
            int nchars;
           /* Try to print in the allocated space. */
            nchars = snprintf (buffer, size, "value of %s is %s",
                               name, value);
            if (nchars >= size)
                /* Reallocate buffer now that we know
                   how much space is needed. */
                buffer = (char *) xrealloc (buffer, nchars + 1);
                /* Try again. */
                snprintf (buffer, size, "value of %s is %s",
                          name, value);
            /* The last call worked, return the string. */
            return buffer;

     In practice, it is often easier just to use `asprintf', below.

     *Attention:* In the GNU C library version 2.0 the return value is
     the number of characters stored, not including the terminating
     null.  If this value equals `SIZE - 1', then there was not enough
     space in S for all the output.  This change was necessary with the
     adoption of snprintf by ISO C9x.

 Andreas Jaeger
  for pgp-key finger