Subject: Re: Query about return value of snprintf
To: None <email@example.com, firstname.lastname@example.org>
From: Michael Richardson <email@example.com>
Date: 06/17/1999 18:05:57
-----BEGIN PGP SIGNED MESSAGE-----
>>>>> "Chris" == Chris G Demetriou <firstname.lastname@example.org> writes:
Chris> email@example.com writes:
>> The NetBSD man page says that we do:
>> These functions return the number of characters printed (not including
>> the trailing `\0' used to end output to strings).
>> Which is what I expected.
Chris> No, that's part of what it says.
Chris> Further it says:
Chris> snprintf() and vsnprintf() will write at most size-1 of the
Chris> characters printed into the output string (the size'th character
Chris> then gets the ter- minating `\0'); if the return value is greater
Chris> than or equal to the size argument, the string was too short and
Chris> some of the printed characters were discarded.
Okay, I missed that part. I don't mind or object to it, I just didn't see
it. I just prefer that things are consistent.
Chris> I consider the BSD behaviour much preferred to what you quote as
Chris> the GNU libc behaviour.
Me too. It is what I expect. It is also more useful since it tells me how
much space I *should* allocate, as you indicate. I am counting on this
behaviour actually, which is how I noticed this problem.
Chris> If the caller wants to know that the output was truncated, they
Chris> can do a simple comparison in either case. However with the BSD
Chris> return value, they can then go an allocate a right-sized buffer if
Chris> their application needs it, and reformat the complete string.
Chris> From what you've quoted, it doesn't sound like there's any good
Chris> way to figure out the 'right size' of a right-sized buffer with
Chris> the glibc implementation.
>> I realize that this isn't POSIX, but are there any opinions as what is
>> reasonable? I see reasons why the GNU version is useful, but I also
>> see that it may break existing code.
Chris> Actually, see above; i'd say that GNU version is strictly less
Chris> useful than the BSD version, as it returns less information.
As my compat snprintf() is a BSD4.3 version that I ported to StunOS years ago,
I'm just going to enable using it on Linux for now, but I thought I'd ask
some questions first.
:!mcr!: | Solidum Systems Corporation, http://www.solidum.com
Michael Richardson |For a better connected world,where data flows faster<tm>
Personal: firstname.lastname@example.org. PGP key available.
Corporate: <A HREF="mailto:email@example.com">firstname.lastname@example.org</A>.
-----BEGIN PGP SIGNATURE-----
Version: PGPfreeware 5.0i for non-commercial use
Comment: Processed by Mailcrypt 3.5.1, an Emacs/PGP interface
-----END PGP SIGNATURE-----