snprintf() return value

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • matevzb

    #1

    snprintf() return value

    The C99 standard describes snprintf() in an awkward way, so it's hard
    (for me) to assume what the result will be in some situations.
    1. The "Descriptio n" section states:
    "... Otherwise, output characters beyond the n-1st are discarded rather
    than being written to the array, and a null character is written at the
    end of the characters actually written into the array."
    2. The "Returns" section states:
    "The snprintf function returns the number of characters that would have
    been written had n been sufficiently large, not counting the
    terminating null character, or a negative value if an encoding error
    occurred. Thus, the null-terminated output has been completely written
    if and only if the returned value is nonnegative and less than n."

    Consider the following code:
    #include <stdio.h>

    int main (void)
    {
    int r;
    double d = -10;
    char str[5];

    r = snprintf (str, 5, "%f", d);
    printf ("r=%d str=%s\n", r, (r 0 && r < 5) ? str : "<INVALID>" );

    return 0;
    }
    Since the precision is missing, it's taken as 6, but snprintf() further
    limits it. My question is, what should be the return value in this
    case:
    a) 5, "str" contains "-10."
    b) 5 (number of characters needed for the double to fit, since it
    didn't fit into "str"), "str" contents invalid
    c) -1 due to an encoding error, "str" contents invalid
    d) something else that I've missed

    My assumption would be 5, but it seems to be incorrect. The following
    are the results from different systems:
    gcc 3.3 (Mac OS X): 10
    gcc 3.4.5 (Windows, mingw): -1
    BC++ 5.5.1 (Windows): 10
    MS VC++ 6.0 and 2005 (Windows, _snprintf() used): -1
    DigitalMars 8.42n (Windows): -1
    I'd also like to know what an "encoding error" means in snprintf()
    case. Isn't it generally related to multibyte/wide characters?
    --
    WYCIWYG - what you C is what you get

  • Jens Thoms Toerring

    #2
    Re: snprintf() return value

    matevzb <matevzb@gmail. comwrote:
    The C99 standard describes snprintf() in an awkward way, so it's hard
    (for me) to assume what the result will be in some situations.
    1. The "Descriptio n" section states:
    "... Otherwise, output characters beyond the n-1st are discarded rather
    than being written to the array, and a null character is written at the
    end of the characters actually written into the array."
    2. The "Returns" section states:
    "The snprintf function returns the number of characters that would have
    been written had n been sufficiently large, not counting the
    terminating null character, or a negative value if an encoding error
    occurred. Thus, the null-terminated output has been completely written
    if and only if the returned value is nonnegative and less than n."
    Consider the following code:
    #include <stdio.h>
    int main (void)
    {
    int r;
    double d = -10;
    char str[5];
    r = snprintf (str, 5, "%f", d);
    printf ("r=%d str=%s\n", r, (r 0 && r < 5) ? str : "<INVALID>" );
    return 0;
    }
    Since the precision is missing, it's taken as 6, but snprintf() further
    limits it. My question is, what should be the return value in this
    case:
    a) 5, "str" contains "-10."
    b) 5 (number of characters needed for the double to fit, since it
    didn't fit into "str"), "str" contents invalid
    c) -1 due to an encoding error, "str" contents invalid
    d) something else that I've missed
    The return value should be 10, since that's how many chars (without
    the trailing '\0') are in "-10.000000", the string you get for an
    unadorned "%f" with -10. The arry 'str' will only contain as many
    of these 10 characters as fit into the string (including the trai-
    ling '\0'), so it would be "-10." in your case. This allows you to
    use snprintf() to find out how many characters you are going to
    need - just call it with 0 as the second argument and it gives you
    the strlen() of the string that would result for a fully success-
    ful call of snprintf(). This number you can then be used to allocate
    exactly as much memory as needed for the resulting string (and you
    can then use the probably slightly faster sprintf();-)
    My assumption would be 5, but it seems to be incorrect. The following
    are the results from different systems:
    gcc 3.3 (Mac OS X): 10
    gcc 3.4.5 (Windows, mingw): -1
    BC++ 5.5.1 (Windows): 10
    MS VC++ 6.0 and 2005 (Windows, _snprintf() used): -1
    DigitalMars 8.42n (Windows): -1
    Looks as if some of these compilers use a non-compliant libc.
    Some of the first implementations of sprintf() (before the
    C99 standard, e.g. the GNU libc 5) did return -1 if the
    resulting string did not fit into memory allowed for writing.
    And this old behaviour does not seem to have been corrected
    in all the implementations you tested.
    I'd also like to know what an "encoding error" means in snprintf()
    case. Isn't it generally related to multibyte/wide characters?
    Yes. As far as I can see you will get an "encoding error" if you
    ask snprintf() to print out a wchar_t string using "%ls", but
    the string does contain data that are not valid wide characters.

    Regards, Jens
    --
    \ Jens Thoms Toerring ___ jt@toerring.de
    \______________ ____________ http://toerring.de

    Comment

    • Clark S. Cox III

      #3
      Re: snprintf() return value

      matevzb wrote:
      The C99 standard describes snprintf() in an awkward way, so it's hard
      (for me) to assume what the result will be in some situations.
      1. The "Descriptio n" section states:
      "... Otherwise, output characters beyond the n-1st are discarded rather
      than being written to the array, and a null character is written at the
      end of the characters actually written into the array."
      2. The "Returns" section states:
      "The snprintf function returns the number of characters that would have
      been written had n been sufficiently large, not counting the
      terminating null character, or a negative value if an encoding error
      occurred. Thus, the null-terminated output has been completely written
      if and only if the returned value is nonnegative and less than n."
      >
      Consider the following code:
      #include <stdio.h>
      >
      int main (void)
      {
      int r;
      double d = -10;
      char str[5];
      >
      r = snprintf (str, 5, "%f", d);
      printf ("r=%d str=%s\n", r, (r 0 && r < 5) ? str : "<INVALID>" );
      >
      return 0;
      }
      Since the precision is missing, it's taken as 6, but snprintf() further
      limits it. My question is, what should be the return value in this
      case:
      a) 5, "str" contains "-10."
      b) 5 (number of characters needed for the double to fit, since it
      didn't fit into "str"), "str" contents invalid
      c) -1 due to an encoding error, "str" contents invalid
      d) something else that I've missed
      >
      My assumption would be 5, but it seems to be incorrect. The following
      are the results from different systems:
      gcc 3.3 (Mac OS X): 10
      gcc 3.4.5 (Windows, mingw): -1
      BC++ 5.5.1 (Windows): 10
      MS VC++ 6.0 and 2005 (Windows, _snprintf() used): -1
      DigitalMars 8.42n (Windows): -1
      10 is the correct result. Put simply, Microsoft's version of snprintf is
      broken (Their documentation even claims that snprintf returns a negative
      value if the number of characters to be written exceeds the buffer
      size). Likely, either for compatibility with Microsoft's implementation,
      or because they actually use Microsoft's implementation, mingw and
      DigitalMars return the same result.



      --
      Clark S. Cox III
      clarkcox3@gmail .com

      Comment

      • santosh

        #4
        Re: snprintf() return value


        Clark S. Cox III wrote:
        matevzb wrote:
        The C99 standard describes snprintf() in an awkward way, so it's hard
        (for me) to assume what the result will be in some situations.
        1. The "Descriptio n" section states:
        "... Otherwise, output characters beyond the n-1st are discarded rather
        than being written to the array, and a null character is written at the
        end of the characters actually written into the array."
        2. The "Returns" section states:
        "The snprintf function returns the number of characters that would have
        been written had n been sufficiently large, not counting the
        terminating null character, or a negative value if an encoding error
        occurred. Thus, the null-terminated output has been completely written
        if and only if the returned value is nonnegative and less than n."

        Consider the following code:
        #include <stdio.h>

        int main (void)
        {
        int r;
        double d = -10;
        char str[5];

        r = snprintf (str, 5, "%f", d);
        printf ("r=%d str=%s\n", r, (r 0 && r < 5) ? str : "<INVALID>" );

        return 0;
        }
        Since the precision is missing, it's taken as 6, but snprintf() further
        limits it. My question is, what should be the return value in this
        case:
        a) 5, "str" contains "-10."
        b) 5 (number of characters needed for the double to fit, since it
        didn't fit into "str"), "str" contents invalid
        c) -1 due to an encoding error, "str" contents invalid
        d) something else that I've missed

        My assumption would be 5, but it seems to be incorrect. The following
        are the results from different systems:
        gcc 3.3 (Mac OS X): 10
        gcc 3.4.5 (Windows, mingw): -1
        BC++ 5.5.1 (Windows): 10
        MS VC++ 6.0 and 2005 (Windows, _snprintf() used): -1
        DigitalMars 8.42n (Windows): -1
        >
        10 is the correct result. Put simply, Microsoft's version of snprintf is
        broken (Their documentation even claims that snprintf returns a negative
        value if the number of characters to be written exceeds the buffer
        size). Likely, either for compatibility with Microsoft's implementation,
        or because they actually use Microsoft's implementation, mingw and
        DigitalMars return the same result.
        I think your latter guess is correct. They call the Microsoft supplied
        'C runtime library.'

        Comment

        • brandon.m.skinner@gmail.com

          #5
          Re: snprintf() return value

          OpenWatcom returns 10.

          Comment

          • matevzb

            #6
            Re: snprintf() return value

            On Jan 20, 5:54 pm, j...@toerring.d e (Jens Thoms Toerring) wrote:
            matevzb <mate...@gmail. comwrote:
            Since the precision is missing, it's taken as 6, but snprintf() further
            limits it. My question is, what should be the return value in this
            case:
            a) 5, "str" contains "-10."
            b) 5 (number of characters needed for the double to fit, since it
            didn't fit into "str"), "str" contents invalid
            c) -1 due to an encoding error, "str" contents invalid
            d) something else that I've missed
            The return value should be 10, since that's how many chars (without
            the trailing '\0') are in "-10.000000", the string you get for an
            unadorned "%f" with -10. The arry 'str' will only contain as many
            of these 10 characters as fit into the string (including the trai-
            ling '\0'), so it would be "-10." in your case.
            Ah stupid me, should've paid more attention to "...returns the number
            of characters that would have been written had n been sufficiently
            large".
            This allows you to use snprintf() to find out how many characters you are going to
            need - just call it with 0 as the second argument and it gives you
            the strlen() of the string that would result for a fully success-
            ful call of snprintf(). This number you can then be used to allocate
            exactly as much memory as needed for the resulting string (and you
            can then use the probably slightly faster sprintf();-)
            I remember doing this (non-portably) through the use of FILE pointers
            back when snprintf() wasn't widely available. Since snprintf() seems to
            be working incorrectly on Windows, I might be going back to this anyhow
            =)
            <snip>
            I'd also like to know what an "encoding error" means in snprintf()
            case. Isn't it generally related to multibyte/wide characters?
            Yes. As far as I can see you will get an "encoding error" if you
            ask snprintf() to print out a wchar_t string using "%ls", but
            the string does contain data that are not valid wide characters.
            I thought so. Also, another word of warning to Windows _snprintf()
            users - in case it returns -1, the string may not be null-terminated (I
            don't know what should happen in a correct implementation though).
            Thanks to all for explanations.
            --
            WYCIWYG - what you C is what you get

            Comment

            • Keith Thompson

              #7
              Re: snprintf() return value

              brandon.m.skinn er@gmail.com writes:
              OpenWatcom returns 10.
              For what?

              Pleaes provide context when you post a followup. Google Groups has
              corrected the bug that made this difficult.

              Read <http://cfaj.freeshell. org/google/>.

              --
              Keith Thompson (The_Other_Keit h) kst-u@mib.org <http://www.ghoti.net/~kst>
              San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
              We must do something. This is something. Therefore, we must do this.

              Comment

              • Old Wolf

                #8
                Re: snprintf() return value

                Jens Thoms Toerring wrote:
                My assumption would be 5, but it seems to be incorrect. The following
                are the results from different systems:
                gcc 3.3 (Mac OS X): 10
                gcc 3.4.5 (Windows, mingw): -1
                BC++ 5.5.1 (Windows): 10
                MS VC++ 6.0 and 2005 (Windows, _snprintf() used): -1
                DigitalMars 8.42n (Windows): -1
                >
                Looks as if some of these compilers use a non-compliant libc.
                Some of the first implementations of sprintf() (before the
                C99 standard, e.g. the GNU libc 5) did return -1 if the
                resulting string did not fit into memory allowed for writing.
                >
                And this old behaviour does not seem to have been corrected
                in all the implementations you tested.
                Well, VC++ 6.0 doesn't claim to support C99, so it is OK for it
                to return -1. I wonder if the OP was invoking Digital Mars
                and GCC in C99 mode or not.

                Comment

                • Clark S. Cox III

                  #9
                  Re: snprintf() return value

                  Old Wolf wrote:
                  Jens Thoms Toerring wrote:
                  >>My assumption would be 5, but it seems to be incorrect. The following
                  >>are the results from different systems:
                  >> gcc 3.3 (Mac OS X): 10
                  >> gcc 3.4.5 (Windows, mingw): -1
                  >> BC++ 5.5.1 (Windows): 10
                  >> MS VC++ 6.0 and 2005 (Windows, _snprintf() used): -1
                  >> DigitalMars 8.42n (Windows): -1
                  >Looks as if some of these compilers use a non-compliant libc.
                  >Some of the first implementations of sprintf() (before the
                  >C99 standard, e.g. the GNU libc 5) did return -1 if the
                  >resulting string did not fit into memory allowed for writing.
                  >>
                  >And this old behaviour does not seem to have been corrected
                  >in all the implementations you tested.
                  >
                  Well, VC++ 6.0 doesn't claim to support C99, so it is OK for it
                  to return -1. I wonder if the OP was invoking Digital Mars
                  and GCC in C99 mode or not.
                  >
                  IIRC, the return value was the same in C90/C89. But, I could be wrong as
                  I don't have a copy in front of me.

                  --
                  Clark S. Cox III
                  clarkcox3@gmail .com

                  Comment

                  • Jens Thoms Toerring

                    #10
                    Re: snprintf() return value

                    Clark S. Cox III <clarkcox3@gmai l.comwrote:
                    Old Wolf wrote:
                    Well, VC++ 6.0 doesn't claim to support C99, so it is OK for it
                    to return -1. I wonder if the OP was invoking Digital Mars
                    and GCC in C99 mode or not.
                    IIRC, the return value was the same in C90/C89. But, I could be wrong as
                    I don't have a copy in front of me.
                    As far as I can see there was no snprintf() in C89/90.

                    Regards, Jens
                    --
                    \ Jens Thoms Toerring ___ jt@toerring.de
                    \______________ ____________ http://toerring.de

                    Comment

                    • matevzb

                      #11
                      Re: snprintf() return value

                      On Jan 22, 6:36 pm, j...@toerring.d e (Jens Thoms Toerring) wrote:
                      Clark S. Cox III <clarkc...@gmai l.comwrote:
                      >
                      Old Wolf wrote:
                      Well, VC++ 6.0 doesn't claim to support C99, so it is OK for it
                      to return -1. I wonder if the OP was invoking Digital Mars
                      and GCC in C99 mode or not.
                      IIRC, the return value was the same in C90/C89. But, I could be wrong as
                      I don't have a copy in front of me.
                      As far as I can see there was no snprintf() in C89/90.
                      I'd say Clark probably meant the (gcc) extension in this case.

                      Here is some additional info that I missed the first time:
                      - gcc was invoked in C99 mode (both mingw and Mac versions).
                      - BC++ 5.5 doesn't provide C99, it has its own snprintf() extension,
                      which is a bit different though.
                      - DMC has some C99 features but no switches for it AFAIK. It has
                      _snprintf() which doesn't conform to C99.
                      - VC++ 2005 only supports some C99 features, snprintf() not included.
                      _snprintf() doesn't conform to C99 - same as VC++ 6.0.
                      I might try some other compilers, but it all seems pretty useless.
                      --
                      WYCIWYG

                      Comment

                      • Roland Pibinger

                        #12
                        Re: snprintf() return value

                        On 22 Jan 2007 11:04:04 -0800, "matevzb" <matevzb@gmail. comwrote:
                        >I might try some other compilers, but it all seems pretty useless.
                        Why? AFAICS, you can detect an error on all implementations with
                        soething like:

                        int n = snprintf (...);
                        if (n < 0 || !(n < bufsize)) {
                        // error
                        }

                        Comment

                        • matevzb

                          #13
                          Re: snprintf() return value

                          On Jan 22, 9:11 pm, rpbg...@yahoo.c om (Roland Pibinger) wrote:
                          On 22 Jan 2007 11:04:04 -0800, "matevzb" <mate...@gmail. comwrote:
                          >
                          I might try some other compilers, but it all seems pretty useless.
                          Why? AFAICS, you can detect an error on all implementations with
                          soething like:
                          >
                          int n = snprintf (...);
                          if (n < 0 || !(n < bufsize)) {
                          // error
                          >
                          }
                          Because for n >= bufsize the string is still valid and properly
                          terminated in a conforming implementation - i.e. it's not an error. In
                          the example
                          int r;
                          double d = -10;
                          char str[5];
                          r = snprintf (str, 5, "%f", d);
                          I explicitly specify the string will contain up to 5 characters
                          (4+NUL), even if it means chopping away the double's zeroes. The result
                          however is -1 in non-conforming implementations plus the string isn't
                          null-terminated (at least in VC++).
                          --
                          WYCIWYG

                          Comment

                          • Stefan

                            #14
                            Re: snprintf() return value

                            Why? AFAICS, you can detect an error on all implementations with
                            soething like:
                            >
                            int n = snprintf (...);
                            if (n < 0 || !(n < bufsize)) {
                            // error
                            }
                            That's the right way.

                            shorter:

                            int n = snprintf(...);

                            if (n < 0 || n >= bufsize) {
                            // error
                            }

                            Although not perfect - the best libc reference known to me:


                            Regards,
                            Stefan

                            Comment

                            • Clark S. Cox III

                              #15
                              Re: snprintf() return value

                              Jens Thoms Toerring wrote:
                              Clark S. Cox III <clarkcox3@gmai l.comwrote:
                              >Old Wolf wrote:
                              >>Well, VC++ 6.0 doesn't claim to support C99, so it is OK for it
                              >>to return -1. I wonder if the OP was invoking Digital Mars
                              >>and GCC in C99 mode or not.
                              >
                              >IIRC, the return value was the same in C90/C89. But, I could be wrong as
                              >I don't have a copy in front of me.
                              >
                              As far as I can see there was no snprintf() in C89/90.
                              Indeed, I misremembered.


                              --
                              Clark S. Cox III
                              clarkcox3@gmail .com

                              Comment

                              Working...