Article View: gnu.gcc.bug
Article #6138Re: Why is this possible?
From: Martin Huber
Date: Sun, 08 Dec 1996 00:00
Date: Sun, 08 Dec 1996 00:00
45 lines
2203 bytes
2203 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)
>
>
> .. snip ...
>
>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.
>
gcc is doing right. str is a pointer to an array of characters, and
sprintf() is intended to print to a character array. The bug is, that
you initialized str to point to a fixed string. This is placed by the
compiler into the data segment instead of the segment of uninitialized
data. gcc does not allow to write to initialized strings as default,
and since it can't see at compile-time to what value str will point
during the program execution, it can't give a warning, but will crash
at runtime to show you the bug in the corefile.
Not all compilers do so. Your example should run if you call gcc with
the option -fwritable-strings if you require it. But note, that this
is prone to errors, since you allocate the size of the array by the
length of your string. If sprintf() writes a longer string, you will
get unpredictable results.
Martin
Technical Details
Message-ID:
<58dok3$ne6@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: <58dok3$ne6@nixe.isar.net> X-Deja-AN: 202955350 sender: bug-gcc-request@prep.ai.mit.edu references: <32A687B4.430F@igd.fhg.de> organization: The unconfigured xvnews people x-gateway: relay1.UU.NET from bug-gcc to gnu.gcc.bug; Sun, 8 Dec 1996 01:54:36 EST reply-to: hu@garfield.m.isar.de newsgroups: gnu.gcc.bug