473,699 Members | 2,518 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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

Jan 20 '07 #1
14 13549
matevzb <ma*****@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
Jan 20 '07 #2
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
cl*******@gmail .com
Jan 20 '07 #3

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

Jan 20 '07 #4
OpenWatcom returns 10.

Jan 20 '07 #5
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

Jan 20 '07 #6
br************* **@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) ks***@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.
Jan 20 '07 #7
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.

Jan 21 '07 #8
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
cl*******@gmail .com
Jan 22 '07 #9
Clark S. Cox III <cl*******@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
Jan 22 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
16294
by: Dave | last post by:
Hi, I tried something with 'return value' of a function and i got two different behaviours. My question is: why does method 1 not work? Thanks Dave method 1: here, whatever i choose (ok or cancel), i go to 'webpage.htm' <body>
3
2360
by: tshad | last post by:
I am trying to set up a class to handle my database accesses. I can't seem to figure out how to get the return value from my dataReader from these routines (most of which I got elsewhere). They do work pretty well, except for the change I made to get the return value. For example, I have the following: ********************************************************************** Public Overloads Function RunProcedure( _ ByVal storedProcName...
5
8084
by: Dmitriy Lapshin [C# / .NET MVP] | last post by:
Hi all, I think the VB .NET compiler should at least issue a warning when a function does not return value. C# and C++ compilers treat this situation as an error and I believe this is the right thing to do. And I wonder why VB .NET keeps silence and makes such function return some default value instead. Isn't it error-prone? -- Dmitriy Lapshin
13
7580
by: vashwath | last post by:
Hi all, To test the return value of system I wrote 2 programs which are shown below. Program 1: #include <stdio.h> #include <stdlib.h> int main(void)
20
3590
by: lovecreatesbeauty | last post by:
Hello experts, Is the following code snippet legal? If it is, how can exit() do the keyword return a favor and give a return value to the main function? Can a function call (or only this exit(n)) statement provide both function call and return features of the C programming language? /* headers omitted */ int main (void)
2
2362
by: Eric Lilja | last post by:
Hello, consider this complete program: #include <iostream> #include <string> using std::cout; using std::endl; using std::string; class Hanna {
6
1893
by: Tim Roberts | last post by:
I've been doing COM a long time, but I've just come across a behavior with late binding that surprises me. VB and VBS are not my normal milieux, so I'm hoping someone can point me to a document that describes this. Here's the setup. We have a COM server, written in Python. For completeness, here is the script: ----- testserver.py ----- import pythoncom
2
2678
by: philip | last post by:
hello, i am new to asp.net and sql server, and i have 3 questions for asking: 1. i am writing a store procedure of login validation for my asp.net application and wondering what the different between RETURN and SELECT is. if exists(select * from users where username = @username and password = @password) BEGIN
7
10317
by: Terry Olsen | last post by:
How do I get this to work? It always returns False, even though I can see "This is True!" in the debug window. Do I have to invoke functions differently than subs? Private Delegate Function IsLvItemCheckedDelegate(ByVal ClientID As Integer) As Boolean Private Function IsLvItemChecked(ByVal ClientID As Integer) As Boolean If lvServers.InvokeRequired = True Then lvServers.Invoke(New IsLvItemCheckedDelegate(AddressOf IsLvItemChecked),...
0
8685
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8613
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9172
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8908
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8880
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7745
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6532
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
1
3054
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2008
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.