Reputation: 1
**So recently i came up with a question in an interview it was based on pointers**
void fun(int *p){
int q = 10;
p = &q;
}
int main() {
int r = 20;
int *p = &r;
fun(p);
cout<<*p<<endl;
}
*my question is (1)Justify the result w.r.t the memory allocation like how this is happening?; (2) how to pass this pointer variable by refrence (i wrote *&p in the parameter of void fun()) when i did it i observed that the p is printing a garbage value ,Now first i thought may be fun has different memory allocation and when it takes the address of q from fun function it address changes but that address in main function is pointing to some garbage value ,Am i right and please explain?
Upvotes: 0
Views: 96
Reputation: 98505
void fun(int *&p) {
int q = 10;
// here the object q began its existence
p = &q;
// here you pass the address of that object *out*
// of the function, to the caller
// here the object q ceases to exist
// question: does anyone have now-invalid pointers that
// pointed to that object?
}
You'll of course immediately see that yes, the caller of fun
has a pointer that doesn't point to a valid object (objects that don't exist are by definition invalid). This is undefined behavior. Anything can happen.
Whatever you observe is just as good as what anyone else would observe :) I can make this code pretend to work, or pretend fail on almost any compiler - it's only a matter of arranging things in a certain way. That doesn't make the code any more valid, of course, and the notion of "working" or "failing" is meaningless anyway: the code is invalid, so as far as C++ is concerned, the discussion about the effects is invalid as well :)
Upvotes: 1