String assignments; Was: When is a cast not a cast?

Chris Torek chris at mimsy.UUCP
Wed May 3 09:37:43 AEST 1989


[char *c = "somestring";]

In article <1814 at leah.Albany.Edu> rds95 at leah.Albany.Edu (Robert Seals) writes:
>Now I always thought this kind of thing was extremely bad form, but
>I've recently seen a couple of code examples that use this. 
>One figures that if ``somestring'' is generated by the compiler somewhere,
>then the assignment will work as expected, because the address of it will
>be copied to ``c''.

This is correct.  The array-11-of-char

	{'s', 'o', 'm', 'e', 's', 't', 'r', 'i', 'n', 'g', '\0'}

is generated (somewhere, somehow) by the compiler; the value of the 
double-quoted expression is thus an object of type

	char [11]

which in this context is immediately converted to one of type

	char *

whose value is the address of the first `s' (wherever the compiler
has placed it).

>But what if the compiler decides that ``somestring'' has finished its
>duty to the program, and overwrites the space it took with something
>else?

Then the compiler has a bug.

Objects created with "foo" have type array-N-of-char and storage class
*static* (and no name, hence no scope class).  They must be created by
the time the runtime system calls main() and live unchanged (unless
overwritten by programmer error) until the program exits.

It is possible for the *programmer* to (attempt to) overwrite the space
with something else:

	strcpy("here is some static string space", "but this is a bad idea");

In particular, this is allowed to fail (with `segmentation fault - core
dumped' or the like) at runtime.  Traditionally, Unix C compilers have
placed these strings in a read/write data area along with other
initialised global and static variables, but newer compilers (gcc) put
them in the text segment instead.
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163)
Domain:	chris at mimsy.umd.edu	Path:	uunet!mimsy!chris



More information about the Comp.lang.c mailing list