Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!swrinde!ucsd!dog.ee.lbl.gov!elf.ee.lbl.gov!torek From: torek@elf.ee.lbl.gov (Chris Torek) Newsgroups: comp.lang.c Subject: Re: Returning pointers to constant strings Keywords: static constant string Message-ID: <12984@dog.ee.lbl.gov> Date: 9 May 91 07:02:28 GMT References: <21139@brahms.udel.edu> Reply-To: torek@elf.ee.lbl.gov (Chris Torek) Distribution: na Organization: Lawrence Berkeley Laboratory, Berkeley Lines: 45 X-Local-Date: Thu, 9 May 91 00:02:28 PDT In article <21139@brahms.udel.edu> weave@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@ee.lbl.gov