int *x;
{
int y;
x = &y;
}
*x = 5;
I think the problem is that x = &y should be changed to x = y. However, I still don't know why it would crash?
int *x;
{
int y;
x = &y;
}
*x = 5;
I think the problem is that x = &y should be changed to x = y. However, I still don't know why it would crash?
The lifetime of int y
ends at the }
token. Since the pointer x
was pointing at y
, we now call x
a "dangling pointer". Dereferencing a dangling pointer using *x
is undefined behavior, which might cause a crash or other nasty things, if you're lucky.
x
is assigned address of y
on line 5. On line 6 y
is destroyed. On line 7 you trying to write in variable, which address contained in x
. Which was destroyed. So you are trying to write into non-existing variable, which leads to undefined behavior.