This is the mail archive of the
gcc@gcc.gnu.org
mailing list for the GCC project.
Re: rationale for eliding modifications to string constants
- From: "Uday P. Khedker" <uday at cse dot iitb dot ac dot in>
- To: Godmar Back <godmar at gmail dot com>
- Cc: gcc at gcc dot gnu dot org
- Date: Tue, 14 Sep 2010 23:50:11 +0530
- Subject: Re: rationale for eliding modifications to string constants
- References: <AANLkTimnOZ2pTOEx3E0Yq+pT+b21ikxcE4SWFYZtzfhb@mail.gmail.com> <AANLkTi=O2ukLEZQkiF2spJM8p_mqD-RE5rLJK3FBH7f_@mail.gmail.com>
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?