Article View: gnu.gcc.bug
Article #6134Re: Why is this possible?
From: Alex Martelli
Date: Fri, 06 Dec 1996 00:00
Date: Fri, 06 Dec 1996 00:00
60 lines
2671 bytes
2671 bytes
luckas@igd.fhg.de (Volker Luckas) writes:
>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:
I'm not sure why this should be "astonishing", actually.
>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.
There is nothing illegal about that sprintf() call -- just the
questionable use of "%lf", and you do get a warning about that
one with -Wall. sprintf() takes as its first argument a char*,
you are supplying it with a char*, what's illegal about that?
What is, not illegal, but VERY questionable, is initializing a
char* to a literal character string; however, the ANSI C standard
deems that to be legal. If the first line was something like:
char * str = (char*)123456;
you wouldn't be particularly astonished to see the resulting
program crash in some cases and not in others, would you? At
least, I wouldn't be.
>Is there any possibility to avoid this kind of behaviour ???
You can add the -Wwrite-strings flag to your compilation line
in order to make a literal character string evaluate to a
const char *, rather than to a char * as the ANSI C standard
mandates. If you do that, you'll get a warning about const
being implicitly cast away in the "char* str = ..." line.
Alex
--
DISCLAIMER: these are MY personal opinions and viewpoints, NOT connected
in any way with my employer, nor any other organization or individual!
Email: martelli@cadlab.it -- Phone: +39 (51) 597 313 [Fax: 597 120]
Cad.Lab S.p.A., v. Ronzani 7/29, 40033 Casalecchio (BO), Italia
Technical Details
Message-ID:
<E1zIpq.73L@cadlab.it>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: martelli@cadlab.it (Alex Martelli) Subject: Re: Why is this possible? Date: 1996/12/06 Message-ID: <E1zIpq.73L@cadlab.it> X-Deja-AN: 202659741 sender: news@cadlab.it references: <32A687B4.430F@igd.fhg.de> organization: CAD.LAB S.p.A., Bologna, Italia x-gateway: relay4.UU.NET from bug-gcc to gnu.gcc.bug; Fri, 6 Dec 1996 04:32:07 EST newsgroups: gnu.gcc.bug