Talk About Network

Google


Register and Login
Nick
Password
Register create new account Sign up is FREE and you can post replies, new topics, bookmark posts and more!
Recover lost password


Programming > C > sprintf behavie...
Latest [ Topics | Posts ] Archive Post A New Topic Post a Reply
<< Topic < Post Post 1 of 8 Topic 24951 of 27671
Post > Topic >>

sprintf behavies different than printf

by google@[EMAIL PROTECTED] Mar 14, 2008 at 01:38 PM

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("\nsprintf: ");
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
 




 8 Posts in Topic:
sprintf behavies different than printf
google@[EMAIL PROTECTED]   2008-03-14 13:38:21 
Re: sprintf behavies different than printf
Eric Sosman <Eric.Sosm  2008-03-14 16:50:16 
Re: sprintf behavies different than printf
Ben Pfaff <blp@[EMAIL   2008-03-14 13:52:29 
Re: sprintf behavies different than printf
Martien Verbruggen <mg  2008-03-15 08:18:09 
Re: sprintf behavies different than printf
Martin Ambuhl <mambuhl  2008-03-14 18:04:10 
Re: sprintf behavies different than printf
spambait@[EMAIL PROTECTED  2008-03-15 01:18:16 
Re: sprintf behavies different than printf
google@[EMAIL PROTECTED]   2008-03-14 22:56:33 
Re: sprintf behavies different than printf
Richard Heathfield <rj  2008-03-15 07:54:58 

Post A Reply:
  Go here to Signup

AddThis Feed Button


About - Advertising - Contact - Frequently Asked Questions - Privacy Policy - Terms of Use - Signup

Contact
tan12V112 Sat Oct 11 8:46:55 CDT 2008.