Re: snprint rationale?

Discussion in 'C Programming' started by Michael Wojcik, Nov 22, 2004.

  1. In article , Michael B Allen <> writes:
    > What is the rationale for snprintf to "return the number of characters
    > (excluding the trailing '\0') which would have been written to the final
    > string if enough space had been available"?


    Others have already pointed out why this is the Right Thing. It's
    also perhaps worth noting a real-world example of the Wrong Thing:
    Microsoft's _snprintf, which returns -1 for both a too-short buffer
    and a formatting error. *That* is obviously broken: the program
    doesn't know whether enlarging the buffer will correct the problem,
    or no amount of buffer space will fix it.

    Consequently, any program that uses _snprintf and tries to implement
    the reallocate-for-more-space pattern has to either impose some
    arbitrary limit on how large the buffer will get, or try it until
    allocation fails, if there's any possibility of a formatting error.

    (Had Microsoft decided to return distinct error codes, their
    _snprintf would be less efficient than a conforming snprintf, since
    the program would have to heuristically determine the space needed,
    but at least it would work.)

    --
    Michael Wojcik

    Thanatos, thanatos! The labourer, dropping his lever,
    Hides a black letter close to his heart and goes,
    Thanatos, thanatos, home for the day and for ever. -- George Barker
    Michael Wojcik, Nov 22, 2004
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Harald Kirsch
    Replies:
    0
    Views:
    362
    Harald Kirsch
    Jun 14, 2004
  2. Alexander Grigoriev
    Replies:
    0
    Views:
    364
    Alexander Grigoriev
    Sep 12, 2003
  3. Asfand Yar Qazi
    Replies:
    5
    Views:
    353
    Siemel Naran
    Apr 7, 2004
  4. Christopher Benson-Manica

    gets() rationale

    Christopher Benson-Manica, Dec 2, 2003, in forum: C Programming
    Replies:
    52
    Views:
    1,389
    Mark McIntyre
    Dec 15, 2003
  5. Michael B Allen

    snprint rationale?

    Michael B Allen, Nov 22, 2004, in forum: C Programming
    Replies:
    27
    Views:
    1,872
    Chris Torek
    Nov 27, 2004
Loading...

Share This Page