string assignment in C

Juergen Wagner gandalf at csli.STANFORD.EDU
Mon Oct 17 13:28:18 AEST 1988


In article <1414 at imagine.PAWL.RPI.EDU> George Kyriazis writes:
...
>        p1 = "abc";
>        p2 = "abc";
>p1 and p2 will have different value, since the strings are not the same
>(they have the same contents, but physically should be different).

Hmmm....

>Is that a right assumption?

I don't think so. Look, what is the same, is not the pointer to those strings.
The contents of the respective memory locations are the same (happen to be).

There is a difference between e.g. ints and those strings: ints fit into
a register and can be 'in-line' coded, strings can't. If the compiler finds
a line
	foo = 6;
and another line
	bar = 6;
then these values might be transformed into instructions loading the value
6 directly into the locations of foo and bar (i.e. without evaluating a lot).

On the other hand, the lines
	p1 = "abc";
	p2 = "abc";
do not allow to do that in general. The optimization is to assign a fixed
memory location to each of those strings, and optimize the use of their
addresses. Usually, strings like these are stored in the static area of the
data space. They have to be distinct unless the compiler can make assumptions
like "static data are read-only and can therefore be merged into the text
space". If you want to share then, use xstr(1) to get shared strings.

-- 
Juergen "Gandalf" Wagner,		   gandalf at csli.stanford.edu
Center for the Study of Language and Information (CSLI), Stanford CA



More information about the Comp.lang.c mailing list