snprintf() return value

M

matevzb

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 "Description" 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?
 
J

Jens Thoms Toerring

matevzb said:
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 "Description" 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
 
C

Clark S. Cox III

matevzb said:
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 "Description" 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.
 
S

santosh

Clark said:
matevzb said:
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 "Description" 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.'
 
M

matevzb

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
=)
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.
 
O

Old Wolf

Jens said:
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.
 
C

Clark S. Cox III

Old said:
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.
 
J

Jens Thoms Toerring

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
 
M

matevzb

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.
 
R

Roland Pibinger

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
}
 
M

matevzb

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++).
 
S

Stefan

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:
http://www.delorie.com/djgpp/doc/libc

Regards,
Stefan
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top