temp....is used wrong in call to sprintf or snprintf.
If copying takes place btewee开发者_StackOverflown objects that overlap as a result of a call to sprintf() or snprintf(), results are undefined.
This doesn't provoke a warning from gcc, even with -Wall -Wextra -pedantic
:
#include "stdio.h"
int main (void) {
char xx[1000] = "hello";
sprintf (xx, "xyzzy plugh %s", xx);
printf ("%s\n", xx);
return 0;
}
However, the reason why this is considered a bad idea can be seen from the output. Rather than getting:
xyzzy plugh hello
as a normal person may expect, you actually get:
xyzzy plugh xyzzy plugh
but, as with all undefined behaviour, your mileage may vary.
The definitive reference is the C99 standard, section 7.19.6.6 The sprintf function
, which states:
The sprintf function is equivalent to fprintf, except that the output is written into an array (specified by the argument s) rather than to a stream. A null character is written at the end of the characters written; it is not counted as part of the returned value. If copying takes place between objects that overlap, the behavior is undefined.
The C++ standard (well, actually the C++0x draft, but it's surely due any day now, hopefully - c'mon guys, get it out there) references this since it incorporates parts of the C standard as deprecated functionality.
精彩评论