For the following code, this is how i understand: Reference to pointer x is passed to function f, val get the address of y which is a local variable. So why, after exiting function f, x is ok? y should have been dereferenced. x is equal to 5, and both printf print the same adress.
void f (int ** val)
{
int y = 5 ;
*val = & y;
printf("%d\n", &y);
}
int _tmain(int argc, _TCHAR开发者_运维知识库* argv[])
{
int * x ;
f(&x );
if ( *x == 5 )
printf("%d", x);
}
It is Undefined Behaviour to access memory your program does not own.
The memory space occupied by y
inside the function does not belong to your program once the function finishes, and yet you access it.
Anything could happen.
The worst thing to happen is for the program to behave as you expect.
When this happens, you believe it is ok to do what you did. IT IS NOT OK. Undefined Behaviour is bad.
Also it's not guaranteed that the same undefined behaviour happens on different runs of the program either. It can work as you expect for a while and crash when you demo it to the client (or your boss).
(Some good manifestations of UB are a crash, or lemon juice starting to ooze out of the USB port)
Anything can happen.
x
is pointing to a local variable inside f
which is no longer valid by the time f
returns.
EDIT: Your post doesn't make it clear what you expect should happen, but as described much clearer in other answers, *x
is pointing to memory which you do not own, and reading from *x
is undefined behavior, so all bets are off. If you try to read from *x
and it happens to be 5, it is probably because the value of 5 is still on the stack. Try to insert some calls to printf
immediately after the call to f
, and you will probably get another result.
The y
variable sits on the stack. so you pass an address on the stack to x, and it's a valid address, but with undefined content. if you add another function (like printf
) between the call to f
and the check of *x == 5
you'll probably get a different result (since the stack was changed).
This is a classic...
The variable y
is only alive as long as the function f
is executed. Once it returns, the memory space occupied by y
on the stack can be used for anything else.
y
lives only within f(int**val)
, since it is declared in that scope.
Refering to its address outside of f()
has no clear definition (or as we love to to say: Undefined Behaviour.
Because y might not be valid, but it's value is still in memory. It'll get nasty if you call some other function or do something else which will write on it.
As nearly everyone has already said, it's undefined behavior. The reason you are printing the correct value (5) is because your program hasn't reused that memory, yet. Wait until your program puts something else at that address, then you will see incorrect results.
精彩评论