This is the mail archive of the gcc@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: rationale for eliding modifications to string constants


Interesting example indeed!

Replace the declaration of s to

char s[] = "hello";

and see "Hello" being printed :-)

The point is: in your program is is only a pointer. When you pass s
as a parameter to printf, the compiler assumes that only s is being
used so the (effective) assignment

*s = 'H'

is deleted as dead code when optimization is enabled.

If you do not optimize the program, you get a segmentation fault (rightly so).

When s is converted from pointer to array, the assignment s[0] is not
a dead assignment because the array base address is passed to the
printf function.

Hope that helps.

Uday.
----------------------------------------------------------------------
Dr. Uday Khedker
Professor
Department of Computer Science & Engg.
IIT Bombay, Powai, Mumbai 400 076, India.
email   : uday@cse.iitb.ac.in
homepage: http://www.cse.iitb.ac.in/~uday
phone   : Office - 91 (22) 2572 2545 x 7717, 91 (22) 2576 7717 (Direct)
          Res.   - 91 (22) 2572 2545 x 8717, 91 (22) 2576 8717 (Direct)
----------------------------------------------------------------------

Godmar Back wrote, On Tuesday 14 September 2010 11:08 PM:
int
main()
{
     char * s = (char *)"hello";     // read-only
     printf("%s\n", s);
     s[0] = 'H';    // gcc -O elides this
     printf("%s\n", s);
     return 0;
}

Could someone briefly provide justification/rationale for this decision?


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]