Embedded_Dude
Embedded_Dude

Reputation: 227

Return by value, and by address

#include <iostream>

int Value ()
{
     int x = 90;//creates a variable x
     return x;//returns the value x, into the caller
     //x is destroyed because it is out of scope
}

int * ptr ()
{
     int x = 7;//creates variable x
     return &x;//returns a pointer to x
     //x gets destroyed because it is out of scope
}

Inside main function

      int y = Value ();// y = 7

      int *py = ptr ();
      /* *py = 7, not Undefined Behaviour?? */

I create this code, and in debugging the program, I *py = 7 in my watch window. Shouldn't I get an Undefined behaviour, and the program crash, since py points to an address that have garbage now (x in ptr() is out of scope)

Upvotes: 0

Views: 73

Answers (3)

eerorika
eerorika

Reputation: 238361

Shouldn't I get an Undefined behaviour

Yes. That is what you got.

Shouldn't ... the program crash

No. The standard does not define that the program must crash. Instead, the behaviour is n undefined.

Upvotes: 1

msc
msc

Reputation: 34608

It's become a dangling pointer. which will cause problems if used.

Upvotes: 0

Avizipi
Avizipi

Reputation: 498

The function ptr returns a value, the address of the local variable x. While you end your function the memory model only mark this address (&x) as writeable, but the actual value in the memory will not be deleted. So when you look at the actual values of the memory address py, you will see the value 7 but it could be changed when another function will ask for some memory.

Upvotes: 1

Related Questions