"scope" rules and problems

hi,
The scope rules for pointers r becoming bit of a concern for me as my code crashes randomly..answers to the following should help me out::

<1>
<a>
void f(int* p) {*p=4;}
int main() {int a=5; f(&a); /*is it safe to use 'a' after this ?*/}
<b>
void f(int& p) {p=4;}
int main() {int a=5; f(a); /*is it safe to use 'a' after this ?*/}

<2>
<a>
int* f(){int* p=1; return p;}
int main() {int* a=f(); /*is it safe to use 'a' after this ?*/}
<b>
int f(){int p=9; return p;}
int main() {int &a=f(); /*is it safe to use 'a' after this ?*/}

/*because 'p' should be destroyed once it's scope ends which concurs with the termination of function "f"..so does this also affect "a" ? */

---
thanks
1.a, yes
1.b, yes

2.a,
Your f() returns a pointer which points to memory location 1. This is not a valid pointer. It isn't safe to dereference it neither if f() nor outside it.

2.b,
Your f returns an int. As far as reference is concerned, the code is equivalent to int& a = 9;. Reference is a sort of pointer, but 9 is not an object, it does not have a memory location, you can't point at it.
@hamsterman

thanks fr the analysis..

2.a was a stupid error by me...i meant
int* f() {int a,*p=&a; *p=1; return p;}
...would this be safe?

can u explain why 1.a & 1.b are safe? does end of scope for p mean deletion of p and if so how would 1.a and 1.b be safe?
Last edited on
ustulation wrote:
2.a was a stupid error by me...i meant

int* f() {int a,*p=&a; *p=1; return p;}

...would this be safe?
No it isn't. You're returning a pointer to a variable that's already removed from the stack. It might or might not crash.

ustulation wrote:
can u explain why 1.a & 1.b are safe?
The variable 'a' is still valid and usable when you call 'f()'
Topic archived. No new replies allowed.