sa*****@yahoo.co.in wrote On 05/04/07 16:29,:
Hi Everyone,
I have the following function,
char* sample1()
{
char *p = "india";
return(p);
}
//in this case the memory storing india is not destroyed at the end
of the function, indicating that it wasn't stored in the stack meant
for the function call.
Correct. The nameless array holding the characters
of "india" has what is called "static storage duration,"
just like variables declared with the `static' keyword.
All static objects already exist and have been initialized
when main() is first called, and continue to exist until
the program ends.
However, the following function causes unexpected behavior as
expected ;-)
"Expect the unexpected." Difficult advice to follow,
and probably not the best advice for programmers. They
would do better to "Avoid the unexpected."
char* sample2()
{
char p[] = "india";
return(p);
}
This is perfectly legal! There is, however, one tiny
gotcha: Undefined behavior occurs if the caller makes any
use whatever of the value returned by sample2(). Trying
to call `puts(sample2()()' is obviously off limits, but so
are seemingly harmless uses like `ptr = sample2()' and
`if (sample2() == NULL)'. Only `(void)sample2()' (or an
equivalent) is safe.
Details: The array p[] has "automatic storage duration,"
which lasts from the moment execution enters its block to
the moment execution exits the block. As soon as the block
that is the body of sample2() exits -- at the `return' --
the array p[] ceases to exist, and any pointer that formerly
pointed to any element of p[] has an indeterminate value.
Using an indeterminate value causes undefined behavior.
I tried both the functions in Microsoft Visual C++ 6.0, is it
specified as per the standard that the first case be not stored in the
stack or is it implementation defined?
The implementation decides where to store "india" and
p[]; the Standard has nothing to say about it (the Standard
doesn't even mention "the stack"). Instead, the Standard
specifies the required lifetimes of the various kinds of
objects. The implementation must arrange for the correct
lifetimes, but can do so in any way it pleases.
--
Er*********@sun.com