🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

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

Re: initialized 'global' (extern) char arrays

#1434
From: Mark Beyleveld
Date: Fri, 08 Jan 1993 13:55
50 lines
1926 bytes
jimlynch@netcom.com (Jim Lynch) writes:

>I am given to understand that the storage allocated by
>
>char *x = "abcde" ;
>
>is not writable.

As was also pointed out, the problem is more subtle, in that somewhere
further into the program, one cannot distinguish between the above, and
strings that were malloc'ed.

There are two solutions, depending on what the author intended:

1) If it is supposed to be read-only, declare it as

    const char * const x = "abcde" ; 

Note that this asserts that the value of the pointer may change, but what
is pointed to is constant.

Also, note that unless the constness is deliberately cast away, one
should not be able to attempt to change the data.

2) If it is not to be read-only, 

	char * x = strdup("abdce");

This is ugly, in that twice the storage is required, but now it is legal 
to say free(x);

There is a similar but more subtle problem:

char * x = strdup("abcde");
char * y = new char[6];
(void) strcpy(y, "abcde");

Further down the road, I want to dispose of the data (which is legal,
since both are dynamically allocated). Do I use free or delete? If
new and delete have not been overloaded, most heap manager implementations
would not care, but this is relying on compiler implementation.

One could declare internal coding standards, but if one uses a third-party
library (for which there may be only object code), what then?


-- 
---------------------------------------------------------------------
Mark Beyleveld
Litwin Process Automation
Technical Details
Message-ID: <1993Jan8.135547.26553@litwin.com>
Path: arc1-ca.pugleaf.net!sparky!uunet!dynsim1!mbb
References: <1993Jan7.032458.21941@netcom.com> <9300812.4657@mulga.cs.mu.OZ.AU>

Show Full Headers
Complete Article Headers
Newsgroups: comp.std.c++
Path: arc1-ca.pugleaf.net!sparky!uunet!dynsim1!mbb
From: mbb@litwin.com (Mark Beyleveld)
Subject: Re: initialized 'global' (extern) char arrays
Message-ID: <1993Jan8.135547.26553@litwin.com>
Organization: Litwin Process Automation
References: <1993Jan7.032458.21941@netcom.com> <9300812.4657@mulga.cs.mu.OZ.AU>
Date: Fri, 8 Jan 1993 13:55:47 GMT
Lines: 50