This is the mail archive of the
gcc@gcc.gnu.org
mailing list for the GCC project.
Re: string variables and literals
- To: Eric Lemings <eric dot b dot lemings at lmco dot com>
- Subject: Re: string variables and literals
- From: Joern Rennecke <amylaar at cygnus dot co dot uk>
- Date: Thu, 31 Aug 2000 20:59:12 +0100 (BST)
- CC: gcc at gcc dot gnu dot org, gcc-bugs at gcc dot gnu dot org
> sidster wrote:
>
> > When you have code like:
> >
> > char* p = "some string";
> >
> > 'p' is a pointer to a constant static string. The memory location
> > pointed to by 'p' should not be modifiable.
>
> I'll try to clarify. This is a string literal: "string literal". This
> is a pointer to an array of constant characters: const char* cs. This
> is a pointer to an array of non-constant characters: char* s. Except
> when initialized with a string literal? C'mon.
>
> p is NOT a pointer to a constant static string. p is a pointer to an
> array of non-constant characters. You DON'T get a warning when it is
> initialized and you DON'T get a warning when you pass it to a function
> as a char* such as strcmp. (Well, unless the warning is explictly
> specified.) But you do get a core dump. That's not good behavior IMHO.
>
> > The compiler doesn't warn about this but the user should be smart enough
> > to realize s/he can't modify the character array pointed to by 'p'.
>
> The compiler should at a minimum issue a warning: "assigning constant
> literal to non-constant variable". Personally, I would like to see it
> initialize char* variables just as it does char[] variables. The
> semantics would be more consistent.
That is nonsese, sinze a char* is a pointer, but char[] is an array.
But you can request gcc to allocate string literals non-shared in data
memory with -fwritable-strings, to accomodate broken legacy programs.
> Also, I checked the standard. Modification of variables declared with
> type char* that are intialized with string literals is undefined. So
> technically, gcc is standardized in this respect. But I think gcc
> should ditch the exception that char* variables can be modified UNLESS
> they are initialized with string literals.
You can modify char* variables no matter how they are initialized.
But that is a topic for comp.lang.c