string assignment in C

Doug Gwyn gwyn at smoke.ARPA
Tue Oct 18 01:41:15 AEST 1988


In article <790 at paris.ics.uci.edu> nagel at paris.ics.uci.edu (Mark Nagel) writes:
>|        p1 = "abc";
>|        p2 = "abc";
>|p1 and p2 will have different value, since the strings are not the same
>optimize the program's space usage by sorting and uniq'ing all of the
>strings so that different string constant references all have the same
>physical address.  This is fine since constant strings should be
>read-only objects.

The key is that you are allowed to portably compare pointers only in two
cases:  at least one pointer is a null pointer, or both pointers are
pointers into the same object.  This means that the fact that p1==p2 for
pointers to distinct objects is not a problem, since such comparison is
"undefined".  (Otherwise, the two string objects would have to be given
unique addresses.)  As it stands, if p1 and p2 are pointers to const
char, the storage may be shared, but not if they are pointers to char
(unless the compiler can determine that the pointers and all aliases to
them are not used to modify the contents of the string literals).  Thus
the automatic "dumb" crunching together of string literals is not
permitted in a standard-conforming implementation.

You can accomplish this coalescing yourself in your source code:
	static char abc_str[] = "abc";
	...
	char *p1 = abc_str;
	char *p2 = abc_str;
Whether it is a good idea or not depends on how the pointers are used.



More information about the Comp.lang.c mailing list