Returning pointers to constant strings

Chris Torek torek at elf.ee.lbl.gov
Thu May 9 17:02:28 AEST 1991


In article <21139 at brahms.udel.edu> weave at brahms.udel.edu (Ken Weaverling)
writes:
>Question: Is there anything dangerous with returning pointers to literal
>strings? Is there a portability issue to consider?

Not really.  The only thing even slightly unusual about this is that
while the type of a string literal is `array N of char' (where N is
one more than the number of characters in the string), the array itself
may, but need not, be placed in read-only (`const') memory.

Thus, the difference between:

	char *f(void) { return "hello"; }

and

	char *f(void) { static char r[] = "hello"; return r; }

is that

	strcpy(f(), "world");

has a well-defined meaning only with the second f().

>Is it just bad practice?

As with anything even vaguely stylistic, different people will hold
different opinions.  For whatever it is worth, I believe this is fine;
you merely must note that the resulting string should not be replaced
as in the strcpy() example above.

>In the local newsgroup at Univ of Del, the consensus was that it would be
>a bad idea, due to systems such as Mess/DOS that might use code overlays,
>and the constant string might be stored in a code overlay that would not
>always be resident.

The local newsgroup is wrong in claiming that overlay systems would be
permitted to do this, but may be right if it claims that some existing,
broken implementation does.  If you want to run on every broken
implementation, you have quite a tough job (you will probably have to
use only the type `int' and only static variables and no more than
three functions and no more than fifty lines of code and ... :-) ).
-- 
In-Real-Life: Chris Torek, Lawrence Berkeley Lab CSE/EE (+1 415 486 5427)
Berkeley, CA		Domain:	torek at ee.lbl.gov



More information about the Comp.lang.c mailing list