Red Hat Bugzilla – Bug 216590
gcc -O2 -D_FORTIFY_SOURCE=2 truncates string
Last modified: 2007-11-30 17:11:49 EST
Description of problem:
Reuse same buffer in sprintf, i.e.,
sprintf(buffer, "%s+%d", buffer, 123456)
gives "+123456" instead of "ABCDEF+123456", i.e. buffer is truncated first to
"\0" before concatenating with "+123456".
Happens only with -D_FORTIFY_SOURCE=2 -O2
-O2 OR -D_FORTIFY_SOURCE=2 separately are ok.
Version-Release number of selected component (if applicable):
Steps to Reproduce:
1. Test file
int main(int argc, char** argv)
sprintf(buffer, "%s+%s", buffer, "123456");
2. Compile test file:
gcc -o testing testing.c -O2 -Wp,-D_FORTIFY_SOURCE=2
The testcase is invalid. Please read:
"If copying takes place between objects that overlap as a result of a call to
sprintf() or snprintf(), the results are undefined."
That's the exact case here, and any result is conforming undefined behavior.
ISO C99 has similar wording for this.
Aaaah - tks - audacious in Fedora Extras uses exactly this (undefined) construct
and is generating bad strings.
sprintf(buffer, "%s+%d", buffer, LBA(info->track[i]));
this is how I encountered the problem. I have referred this bug to audacious
maintainer (see 216571) and upstream.