Article View: gnu.gcc.bug
Article #6139Re: Why is this possible?
From: Martin Huber
Date: Sun, 08 Dec 1996 00:00
Date: Sun, 08 Dec 1996 00:00
47 lines
2271 bytes
2271 bytes
In article <32A687B4.430F@igd.fhg.de>, luckas@igd.fhg.de (Volker Luckas) writes:
>Hello all,
>
>it was very astonishing for me to recognize that the following piece of
>source code is accepted by gcc 2.7.2 (Solaris 2.5) without giving a
>warning if gcc is called in the following way:
>
>gcc test.c -o test
>
>#include <string.h>
>
>int main( )
>{
> char* str = "0.12345678";
> double val = 1.11111111;
>
> sprintf( str, "%lf", val );
>
> printf( "Result: %s\n", str );
>
> return 0;
>}
>
>The generated binary crashes if started afterwards. Interestingly this
>does not happen if you compile the source with cc from the Solaris 2.5
>Compiler package or even with gcc 2.7.2 running under IRIX 5.3
>
>Compiling the source with -Wall gives you a warning about implicitely
>defined functions but no warning about the illegal sprintf( ) call.
>
The call to sprintf is not illegal. str is a pointer to a character
array, and sprintf is intended to print into it.
The bug is that you initialize str to a fixed string "...", which is
located in the initialized data segment. As default, gcc goes not allow
to overwrite it, and since there is no way to detect at compile time where
your pointer str will point to during execution (a pointer may change!),
gcc can't give a warning, but the program will crash at runtime to show
you the error in the corefile (or gdb).
Not all compilers do so. If you need this behaviour, use
gcc -fwritable-strings
and your example should run. But notice that you are inviting trouble
doing so. The size of str is defined by the length of "...", and if
the string produced by sprintf() is longer you get unpredictible results.
Martin
Technical Details
Message-ID:
<58euk7$agu@nixe.isar.net>Path:
arc1-ca.pugleaf.net!unknown!not-for-mailReferences:
<32A687B4.430F@igd.fhg.de>Show Full Headers
Complete Article Headers
X-Google-Language: ENGLISH,ASCII-7-bit X-Google-Thread: 113d02,8c9ed5628eb65d44 X-Google-Attributes: gid113d02,public From: hu@garfield.m.isar.de (Martin Huber) Subject: Re: Why is this possible? Date: 1996/12/08 Message-ID: <58euk7$agu@nixe.isar.net> X-Deja-AN: 203006284 sender: bug-gcc-request@prep.ai.mit.edu references: <32A687B4.430F@igd.fhg.de> organization: The unconfigured xvnews people x-gateway: relay6.UU.NET from bug-gcc to gnu.gcc.bug; Sun, 8 Dec 1996 12:42:13 EST reply-to: hu@garfield.m.isar.de newsgroups: gnu.gcc.bug