🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: comp.std.c
Article #3913

Re: Placement of string literals

#3913
From: Zefram
Date: Mon, 04 Sep 1995 12:35
45 lines
2197 bytes
Kurt Watzka <ua302aa@sun2.lrz-muenchen.de> wrote:
>Obviously, there are compilers that handle
> 
>   char *foo = "Hello world";
> 
>different form
> 
>   const char *bar = "Hello world";
> 
>as far as the placement of the string literal is concerned. String   
>literals are arrays of "const char". This implies that they can
>be placed in read only memory. Does the definition of "foo" somehow
>prevent this placement?

No.  The characters that make up the string are const, even if the
pointer doesn't agree.  It's undefined behaviour to try to modify any
of the characters.  (I get a SIGSEGV here.)

To look at it another way, the two definitions above could be
reimplemented as:

const char __foo[] = {'H','e','l','l','o',' ','w','o','r','l','d','\0'};
char *foo;
foo = (char *) __foo;

const char __bar[] = {'H','e','l','l','o',' ','w','o','r','l','d','\0'};
const char *bar;
bar = (const char *) __bar;

The casts, which in normal definitions are implicit, are the key to
this.  In the case of bar, the cast is a no-op, save for the decay of
an array to a pointer.  In the case of foo, the cast discards the
constness of the characters.  A good compiler ought to be able to warn
about this, but there's too much old code (that was written when const
wasn't available) for this to be a default on most compilers.

>In other words, what is wrong with the statement: "String literals
>are arrays of const char, and hence may be placed in a read only 
>region of storage, even if they are used to initialize a non const
>char *"?

It's so long that by the time one gets to the end of the statement one
has forgotten what the beginning was.  But it's accurate.

-zefram
Technical Details
Message-ID: <1995Sep4.123536.3152@dcs.warwick.ac.uk>
Path: arc1-ca.pugleaf.net!news.dcs.warwick.ac.uk!not-for-mail
References: <42c4uu$9e5@sparcserver.lrz-muenchen.de>

Show Full Headers
Complete Article Headers
Newsgroups: comp.std.c
Path: arc1-ca.pugleaf.net!news.dcs.warwick.ac.uk!not-for-mail
From: A.Main@dcs.warwick.ac.uk (Zefram)
Subject: Re: Placement of string literals
X-Nntp-Posting-Host: stone
Message-ID: <1995Sep4.123536.3152@dcs.warwick.ac.uk>
Keywords: string literals, const
Sender: news@dcs.warwick.ac.uk (Network News)
Organization: Department of Computer Science, Warwick University, England
References: <42c4uu$9e5@sparcserver.lrz-muenchen.de>
Date: Mon, 4 Sep 1995 12:35:36 GMT