-3
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?

Leon Ma
  • 303
  • 4
  • 13
  • The variable `x` points to goes out of scope when the the program exits the inner scope where `y` is defined. – melak47 Dec 13 '15 at 00:35
  • 1
    `y` is out of scope when its old location is changed. So it is absolutely UNDEFINED BEHAVIOR and can do anything. In practice you'll need some extra complications to make that crash. – JSF Dec 13 '15 at 00:36
  • 1
    **Every** introductory book on C++ explains object lifetimes. You should read [at least one](http://stackoverflow.com/q/388242/1889329). – IInspectable Dec 13 '15 at 00:41
  • I'm voting to close this question as off-topic because it is low quality. – gsamaras Dec 13 '15 at 01:15

2 Answers2

1

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.

aschepler
  • 70,891
  • 9
  • 107
  • 161
0

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.

Revolver_Ocelot
  • 8,609
  • 3
  • 30
  • 48