From mboxrd@z Thu Jan 1 00:00:00 1970 To: 9fans@cse.psu.edu From: Peter Pichler Message-ID: <404e4fd4_2@mk-nntp-2.news.uk.tiscali.com> References: Subject: [9fans] Re: constant string Date: Wed, 10 Mar 2004 09:47:21 +0000 Topicbox-Message-UUID: 28478094-eacd-11e9-9e20-41e7f4b1d025 "Prem Mallappa" wrote: > #include > > int main(void) > { > char *s = "Hello"; > > s[2] = 'z'; > > printf ("%s\n", s); > > return 0; > } > > ------------------------------------------ > > my question is when i compile this in Linux (gcc) i get a segmentation > fault at the second statement of main(), > As far as my knowledge i think this is because in 2nd chapter of K&R book > it is being mentioned that > ' any thing enclosed between " and " is a string constant' so here i am > changing a constant, and i get a segmentation fault ( and i also noticed > that gcc stores the string Hello in read-only datasegment) > > but when i compile the same thing in plan9 C compiler ( both native "8c" > and "pcc" i get a output of "Hezlo") > why this is happenning.. Welcome o the world of undefined behaviour. Modifying (or attempting to) a string literal is one of many instances of UB. It may "work" on one machine or with one compiler, but on another. It may even "work" on Tuesdays only. In other words, do not do it. > sorry if i am posting to wrong group, > thanks in advance > prem Appropriate group, an equally appropriate answer. Peter