Operating System - Linux
1753936 Members
9956 Online
108811 Solutions
New Discussion юеВ

Re: Problem with sprintf in HP aC++/ANSI C B3910B A.05.55 [Dec 04 2003]

 
desastre22
New Member

Problem with sprintf in HP aC++/ANSI C B3910B A.05.55 [Dec 04 2003]

Hello,

I use you compiler:

HP aC++/ANSI C B3910B A.05.55 [Dec 04 2003]

We have a problem with sprintf

I have this program:

int main()
{
char var2[21]="";

strcpy(var2,"");
strcpy(var2,"06");
sprintf(var2,"20%s",var2);
printf("%s\n",var2);
}

And the program shows this:

2020


Why? the program must be show:

2006

Please tell me how repair this problem.

Thank you!
2 REPLIES 2
A. Clay Stephenson
Acclaimed Contributor

Re: Problem with sprintf in HP aC++/ANSI C B3910B A.05.55 [Dec 04 2003]


You "repair" the compiler by writing better code.

Look at your sprint():
sprintf(var2,"20%s",var2);

sprintf processes the format string from left to write. Note that the 1st thing that is does is copy "20" to var. Next your %s is instantiated using the contents of var2 (which are now "20") so that "2020" is trhe expected output. Please don't bother to explain how you want sprintf to behave; this is a case of that dumb computer (and function) doing exactly what it was told to do.

To convince yourself that I am correct, make this change:
sprintf(var2,"%s20",var2);
The output will be "0620" just as expected.

Note that arrays are passed by reference rather than by value so that there is no copy of var2 passed to sprintf, merely an address -- in this case, the same address twice pushed on the stack.
If it ain't broke, I can fix that.
Dennis Handly
Acclaimed Contributor

Re: Problem with sprintf in HP aC++/ANSI C B3910B A.05.55 [Dec 04 2003]

Note: A.05.55 is obsolete, the latest is A.06.07, PHSS_34351.

> You "repair" the compiler by writing better code.

As Clay said, this code is illegal.

>sprintf processes the format string from left to right.

This is undefined. The C99 Standard says 7.19.6.5(2)
If copying takes place between objects that overlap, the behavior is undefined.