473,386 Members | 1,698 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

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("\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
Mar 14 '08 #1
3 2592
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("\nsprintf: ");
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 "interesting" 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("\nsprintf: ");
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);int main(void){unsigned long b[]
={0x67dffdff,0x9aa9aa6a,0xa77ffda9,0x7da6aa6a,0xa6 7f6aaa,0xaa9aa9f6,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)break;else default:continue;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("\nsprintf: ");
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
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
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
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...
2
by: aap | last post by:
I have the following code #define MAX 32 struct A { char carr; int iarr; int i; }; void main() {
5
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...
12
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" ???...
6
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? ...
15
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...
5
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
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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...
0
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,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

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.