🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: comp.std.c++
Article #1419

Re: initialized 'global' (extern) char arrays

#1419
From: Steve Clamage
Date: Thu, 07 Jan 1993 17:44
37 lines
1705 bytes
jimlynch@netcom.com (Jim Lynch) writes:

>I am given to understand that the storage allocated by

>char *x = "abcde" ;

>is not writable. In terms of whatever standard exists, is it exactly the same as

>const char *x = "abcde" ;  // ?

It is not exactly the same.  Whether literal strings are writeable is
up to the implementation, not mandated by the Standard.  The sequence
	char *p = "abcde";
	*p = 'z';
is allowed to succeed or fail.  The compiler is not obligated to warn you
that you are writing to readonly storage if that is the case.  For one
thing, it can't always tell.  Consider
	void foo(char *q) { *q = 'z'; }
This function could be called from another translation unit.  It is
legal to pass such a function a pointer to a literal string, and the
function doesn't know what is being passed to it.  It could fail only
at run time, absent cross-module type checking.

The sequence
	const char *p = "abcde";
	*p = 'z';
must be diagnosed as an error.  Type "const char*" is not the same
type as "char *".

Three rules for happy living:
1. Don't assume you can write to literal strings.
2. Don't assign or pass a literal string to a char*.
3. Declare a parameter to be const char* if the string is only read.
(Hmmm.  Maybe this is too narrow a view of happy living...)
-- 

Steve Clamage, TauMetric Corp, steve@taumet.com
Technical Details
Message-ID: <1993Jan7.174401.8494@taumet.com>
Path: arc1-ca.pugleaf.net!sparky!uunet!taumet!steve
References: <1993Jan7.032458.21941@netcom.com>

Show Full Headers
Complete Article Headers
Newsgroups: comp.std.c++
Path: arc1-ca.pugleaf.net!sparky!uunet!taumet!steve
From: steve@taumet.com (Steve Clamage)
Subject: Re: initialized 'global' (extern) char arrays
Message-ID: <1993Jan7.174401.8494@taumet.com>
Organization: TauMetric Corporation
References: <1993Jan7.032458.21941@netcom.com>
Date: Thu, 7 Jan 1993 17:44:01 GMT
Lines: 37