G
Guest
Harald said:Flash said:(e-mail address removed) wrote:
Harald van Dijk wrote:
Keith Thompson wrote:
[...]
No, it isn't. When s reaches the end of its lifetime (at the end of
foo(), the value of p becomes indeterminate. Dereferencing p, or even
looking at its value, invokes undefined behavior. (The latter isn't
likely to cause any visible problems on most systems, but you should
still avoid it.)
The word "looking" is vague. Does it mean that I can't do something
like this?
#include <stdio.h>
static int* foo(void);
int main(void)
{
int *p;
p = foo();/* legal? */
printf("Pointer was %p\n", (void*)p);/* legal? */
return 0;
}
static int* foo(void)
{
int i;
return &i;
}
Any reference to the value of p after foo() returns invokes undefined
behavior. For that matter, I think assigning the result of foo() to p
in the first place invokes UB.
A question: what about just "foo();" (without an assignment)? Is the value
allowed to be read before discarding it?
No, I would say it isn't; otherwise the implementation would
be doing something not done by the abstract machine, violating
the as-if rule. To say it another way, the implementation is
allowed to read the value, but must behave as if it doesn't.
I agree with ena8t8si and would add in support that in C89 at least if
you fell off the end of the function without returning a value the
program would still be strictly conforming *if* you did not use the
value. So if "foo();" is fine if nothing is returned it must surely
still be fine if a value you are not allowed to use is returned.
Thanks. Now for my followup question: how does this affect an
expression statement consisting of a single volatile variable? Is a
read allowed?
Not just allowed, but required.
So the result of an expression-statement must not be read if it is a
function call, and must be read if it is a variable (and all exceptions
are results of the as-if rule)? Where does the standard make this
distinction?