No. No more than a program that returned a "local int" would be
undefined. Problems come from returning pointers *to* things that are
local (specifically local things that are about to disappear).
Sorry I didn't get you.
If we write
char * fun()
{
char p[]="happy";
return p;
}
Then would it be undefined behaviour and why?
Your question is found in the C-FAQ.
7.5a: I have a function that is supposed to return a string, but
when
it returns to its caller, the returned string is garbage.
A: Make sure that the pointed-to memory is properly allocated.
For example, make sure you have *not* done something like
char *itoa(int n)
{
char retbuf[20]; /* WRONG */
sprintf(retbuf, "%d", n);
return retbuf; /* WRONG */
}
One fix (which is imperfect, especially if the function in
question is called recursively, or if several of its return
values are needed simultaneously) would be to declare the
return
buffer as
static char retbuf[20];
See also questions 7.5b, 12.21, and 20.1.
References: ISO Sec. 6.1.2.4.
7.5b: So what's the right way to return a string or other aggregate?
A: The returned pointer should be to a statically-allocated
buffer
(as in the answer to question 7.5a), or to a buffer passed in
by
the caller, or to memory obtained with malloc(), but *not* to
a
local (automatic) array.
See also question 20.1.
P.S.
I think that the ISO reference should be 6.2.1.4 rather than 6.1.2.4
From WG14/N1256 Committee Draft — Septermber 7, 2007 ISO/IEC 9899:TC3,
pages 29, 30:
"6.2.1 Scopes of identifiers"
Item 4:
"4 Every other identifier has scope determined by the placement of its
declaration (in a declarator or type specifier). If the declarator or
type specifier that declares the identifier appears outside of any
block or list of parameters, the identifier has file scope, which
terminates at the end of the translation unit. If the declarator or
type specifier that declares the identifier appears inside a block or
within the list of parameter declarations in a function definition,
the identifier has block scope, which terminates at the end of the
associated block. If the declarator or type specifier that declares
the identifier appears within the list of parameter declarations in a
function prototype (not part of a function definition), the identifier
has function prototype scope, which terminates at the end of the
function declarator. If an identifier designates two different
entities in the same name space, the scopes might overlap. If so, the
scope of one entity (the inner scope) will be a strict subset of the
scope of the other entity (the outer scope). Within the inner scope,
the identifier designates the entity declared in the inner scope; the
entity declared in the outer scope is hidden (and not visible) within
the inner scope."