This is the mail archive of the
gcc-bugs@gcc.gnu.org
mailing list for the GCC project.
Re: string variables and literals
- To: gcc at gcc dot gnu dot org, gcc-bugs at gcc dot gnu dot org
- Subject: Re: string variables and literals
- From: Eric Lemings <eric dot b dot lemings at lmco dot com>
- Date: Thu, 31 Aug 2000 10:37:29 -0400
- Organization: Lockheed Martin Corporation
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.
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.
Eric.