473,748 Members | 10,737 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

sprintf behavies different than printf

Consider the following code:

char str[100];
char str2[100];
strcpy(str, "%alfa% %beta% d%100%d %gamma% %delta%");
printf("printf: ");
printf("1%s2", str);
printf("\nsprin tf: ");
sprintf(str2, "1%s2", str); //Interesting stuff happens here
printf(str2);
printf("\n");

The code should format the string "1%s2" by replacing %s with "%alfa%
%beta% d%100%d %gamma% %delta%". First printf is used, and then
sprintf. The output should be:

printf: 1%alfa% %beta% d%100%d %gamma% %delta%2
sprintf: 1%alfa% %beta% d%100%d %gamma% %delta%2

However, this is not what happens i either Visual C++ 6.0, Visual C++
2003 and GCC (version 4 I think, compiled and tested in Linux). In all
these compilers printf works as expected, but fails with sprintf where
the result is either a crash or a malformed string. The problem seems
to be that the %-character is used in the argument which, as fair as I
know, shouldn't be any problem.

If I replace %s with "%%alfa%% %%beta%% d%%100%%d %%gamma%% %%delta%%"
the output will instead by (at least in Visual C++ 2003):

printf: 1%%alfa%% %%beta%% d%%100%%d %%gamma%% %%delta%%2
sprintf: 1%alfa% %beta% d%100%d %gamma% %delta%2

So when using sprintf %% is replaced by % which should be the is these
characters where written in the format string, but this is a very
different case.

Unless I have misunderstand the specification of sprintf there is a
quite critical bug in sprintf and this in several compilers. Is this
an known problem? Are more compilers affected? Why are the problem in
both Visual C++ and GCC? Isn't this very interesting? :-)

PEK
Mar 14 '08 #1
3 2619
go****@pekspro. com wrote:
Consider the following code:

char str[100];
char str2[100];
strcpy(str, "%alfa% %beta% d%100%d %gamma% %delta%");
printf("printf: ");
printf("1%s2", str);
printf("\nsprin tf: ");
sprintf(str2, "1%s2", str); //Interesting stuff happens here
Not very. What happens on the next line is far more
interesting, if undefined behavior is "interestin g" to you.
printf(str2);
This is equivalent to

printf("1%alfa% %beta% d%100%d %gamma% %delta%2");

.... which is faulty on several counts: Undefined conversion
specifiers ("%a", "% ", "%b", "%100%", "%2"), and specifiers
without values for them to convert ("%g", "%d"). printf()
can do whatever it pleases; Garbage In, Garbage Out.

--
Er*********@sun .com

Mar 14 '08 #2
go****@pekspro. com writes:
Consider the following code:

char str[100];
char str2[100];
strcpy(str, "%alfa% %beta% d%100%d %gamma% %delta%");
printf("printf: ");
printf("1%s2", str);
printf("\nsprin tf: ");
sprintf(str2, "1%s2", str); //Interesting stuff happens here
printf(str2);
You mean:
printf("%s", str2);
Otherwise the % directives in str2 are interpreted by printf(),
with undefined results.
printf("\n");
--
char a[]="\n .CJacehknorstu" ;int putchar(int);in t main(void){unsi gned long b[]
={0x67dffdff,0x 9aa9aa6a,0xa77f fda9,0x7da6aa6a ,0xa67f6aaa,0xa a9aa9f6,0x11f6} ,*p
=b,i=24;for(;p+ =!*p;*p/=4)switch(0[p]&3)case 0:{return 0;for(p--;i--;i--)case+
2:{i++;if(i)bre ak;else default:continu e;if(0)case 1:putchar(a[i&15]);break;}}}
Mar 14 '08 #3
go****@pekspro. com wrote:
Consider the following code:
[replaced with the legal program, with one extra line:]
#include <stdio.h>
#include <string.h>

int main(void)
{
char str[100];
char str2[100];
strcpy(str, "%alfa% %beta% d%100%d %gamma% %delta%");
printf("printf: ");
printf("1%s2", str);
printf("\nsprin tf: ");
sprintf(str2, "1%s2", str); /* Interesting stuff happens here */
printf(str2);
printf("\n");
printf("%s\n", str2); /* the extra line */
return 0;
}
The code should format the string "1%s2" by replacing %s with "%alfa%
%beta% d%100%d %gamma% %delta%". First printf is used, and then
sprintf. The output should be:

printf: 1%alfa% %beta% d%100%d %gamma% %delta%2
sprintf: 1%alfa% %beta% d%100%d %gamma% %delta%2
No, it should not. The format string in printf(str2) is
"1%alfa% %beta% d%100%d %gamma% %delta%2"
This format string tells printf to expect several additional arguments:
"%a" (in C99) specifies a double to be represented with
hex digits.
(in C90) undefined conversion
"% " undefined (no space is allowed as a flag in "%%")
"%b" undefined conversion
"% d" signed int represented as decimal integer with a leading space
or '-'
"%100" undefined
"%d" signed int represented as decimal integer
"%g" double represented as with "%f" or "%e"
"% " undefined (no space is allowed as a flag in "%%")
"%d" signed int represented as decimal integer
"%2" undefined (no conversion specified, width = 2)

You provide none of these arguments.
See the result of the added line/
Your various guesses are irrelevant. You call printf with a format
string specifying additional atguments which you do not provide.
Mar 14 '08 #4

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

Similar topics

10
9951
by: ios | last post by:
Hi Can someone tell me what is different between below case? strcpy(eventname, "MDCX_RSP"); and sprintf(eventname, "MDCX_RSP"); Thanks, Leon
6
1856
by: hongky gump | last post by:
#include <stdio.h> #include <string.h> char str; char append; .... sprintf(str, "%s%s", str, append); .... is it standard use?
1
3524
by: jimjim | last post by:
Hello, I was wondering about the implications of giving as an argument to sprintf a different data type from the one specified in the format argument. This type of question along with some others are asked below: 1. #include <stdio.h> int main(){ char buffer;
2
4720
by: aap | last post by:
I have the following code #define MAX 32 struct A { char carr; int iarr; int i; }; void main() {
5
3202
by: tjay | last post by:
Hi. I wrote some code using sprintf and atof to store a double as a string of fixed length and to convert it back to a double variable. The string is stored in a char buffer global variable. I'm afraid it might contain bugs though. If I serialize a double, I get a string of the format "-1.0000000000000000e+212". This string gets stored in the buffer. Then, to convert it back into a double, I pass it to the atof function. The problem...
12
4604
by: Henryk | last post by:
Hey there, I have some problems with the following code snippet on a Virtex-4 PowerPC with a GCC based compiler char chData; sprintf(&chData, "%+05.0f", -0.038f); --I get "-000" ??? sprintf(&chData, "%+05.0f", -0.380f); --I get "-000" ??? sprintf(&chData, "%+05.0f", -3.800f); --I get "-0004" ok
6
2662
by: merrittr | last post by:
I am trying to build variables for a function using sprintf. However they don't seem to be proper char strings since submiting literals seems to work fine. Any advice to get me rolling? sprintf( i1, "%s %s \0",v1,v2 ); sprintf( i1, "%s %s \0",v3,v4 ); printf("answer %s\n",add(cTypeCurr,i1,i2)); printf("answer %s\n",add("i","3 i","4 i"));
15
3529
by: krister | last post by:
Hello, I'm working in a quite large system that has some limitations. One of those is that I can't use printf() to get an output on a screen. I'm forced to use a special function, let's call it PrintOnConsole(), to get the output on a console. The problem with PrintOnConsole() is that it only takes strings as input arguments. On the other hand, I'm free to use sprintf(), so I can convert everything I want to print into a string and then...
5
3467
by: Dave | last post by:
Hi, In awk I can do this: var1="x"; temp = sprintf("Variable 1: %s Variable 2: %%s", var1); # now the value of temp is "Variable 1: x Variable 2: %s" var2="y"; printf(temp,var2);
0
8991
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...
1
9321
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
9247
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
8242
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
6796
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...
0
6074
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4602
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3312
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
2
2782
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.