Returning pointers to constant strings
Ken Weaverling
weave at brahms.udel.edu
Tue May 7 01:02:46 AEST 1991
I have scanned the FAQs and have also discussed this topic in a local group,
but would now like to get a few more opinions.
Question: Is there anything dangerous with returning pointers to literal
strings? Is there a portability issue to consider? Is it just bad practice?
Sample code:
char *phredd () {
char *phrogg;
phrogg = "Phredd Phrogg's Phantasy Philm";
return phrogg;
}
*Solutions* to this are many, such as returning a pointer to a static char
array, making the literal a global, strdup()'ing it, or strcpy()'ing it
to another place. I am concerned with the mentioned issue though.
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.
I used gdb against a gcc compiled source to verify that the string was
stored in the code segment just after a function (but not necessarily
the same function that it is used in). I know that it is not a good idea
to alter the string, but that also is not the issue.
Well, I referred to the *bible* for C, the Kernighan and Ritchie book on C,
second edition (for ANSI C). It says on page 194, section A2.6 ...
A string literal, also called a string constant, is a sequence of characters
surrounded by double quotes, as in "...". A string has type "array of
characters" and storage class *static*. Whether identical strings are
distinct is implementation-defined, and the behavior of a program that
attempts to alter a string literal is undefined.
.... and then the definition of static from section A4.1 ...
Static objects may be local to a block or external to all blocks, but in
either case, retain their values across exit from and reentry to functions
and blocks.
So, from above, I infer that there is nothing wrong with the code above.
Any comments? Is it still bad practice from a style standpoint? Thanks!
--
>>>---> Ken Weaverling >>>----> weave at brahms.udel.edu
More information about the Comp.lang.c
mailing list