Article View: comp.std.c
Article #4722Re: Two questions - Pointer equality and ...
From: Dan Pop
Date: Wed, 31 Jan 1996 01:55
Date: Wed, 31 Jan 1996 01:55
64 lines
2251 bytes
2251 bytes
tanmoy@qcd.lanl.gov (Tanmoy Bhattacharya) writes:
>In article <4elq8a$j0b@taurus.fccc.edu> slifker@castor.fccc.edu
>(Michael J. Slifker) writes:
>
> I've compiled the following program with gcc:
>
> -----------
>
> #include <stdio.h>
>
> char *str1 = "Hello, World\n";
> const char *str2 = "Hello, World\n";
>
> int main(void)
> {
> str1[0] = 'J';
> printf("%s", str2);
> return 0;
> }
>
> -----------
>
> ...and it prints out "Jello, World". This seems odd, at least to
> me. Is this a bug, or is the behavior above officially undefined?
>
>Attempt to modify a string literal results in undefined behaviout. Any
>behaviour by the implementation is then valid.
The full answer is in ANSI classic 3.1.4:
Identical string literals of either form need not be distinct. If
the program attempts to modify a string literal of either form, the
behavior is undefined.
So, if we modify main() in the above example to look like this:
int main(void)
{
printf("%d\n", str1 == str2);
return 0;
}
Both "0" and "1" are correct outputs. Different compilers on the same
platform may produce diferent results:
ues5:~/tmp 88> gcc test.c
ues5:~/tmp 89> ./a.out
1
ues5:~/tmp 90> cc test.c
ues5:~/tmp 91> ./a.out
0
This actually explains the (undefined) behaviour observed by the original
poster. There are systems where the attempt to modify a string literal
results in a segmentation fault, because string literals are put in a
read-only memory segment.
Dan
--
Dan Pop
CERN, CN Division
Email: danpop@mail.cern.ch
Mail: CERN - PPE, Bat. 31 R-004, CH-1211 Geneve 23, Switzerland
Technical Details
Message-ID:
<9601310155.AA07417@dxmint.cern.ch>Path:
arc1-ca.pugleaf.net!mail2news.demon.co.uk!hpl3sn03.cern.chReferences:
<4elq8a$j0b@taurus.fccc.edu> <TANMOY.96Jan30150808@qcd.lanl.gov>Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!mail2news.demon.co.uk!hpl3sn03.cern.ch From: Dan Pop <danpop@mail.cern.ch> Newsgroups: comp.std.c Subject: Re: Two questions - Pointer equality and ... Date: Wed, 31 Jan 1996 02:55:01 +0100 Organization: CERN European Lab for Particle Physics Message-ID: <9601310155.AA07417@dxmint.cern.ch> References: <4elq8a$j0b@taurus.fccc.edu> <TANMOY.96Jan30150808@qcd.lanl.gov> X-NNTP-Posting-Host: hpl3sn03.cern.ch X-Newsreader: NN version 6.5.0 #7 (NOV) X-Mail2News-Path: dxmint.cern.ch!hpl3sn03.cern.ch