Possible Duplicate:
Pointer to local variable
Can a local variable's memory be accessed outside its scope?
I have an interesting problem. I have a read function that returns a pointer:
char * myReadFunc() {
char r [10];
//some code that reads data into r.
return r;
}
Now, I call this function to assign info to some variables I have:
char * s;
//Some code to specify where to read from.
s = myReadFunc();
This produces results as I intended.
However, when I do this:
char * s1;
char * s2;
//Some code to specify where to read from.
s1 = myReadFunc();
//Some code to change the read location.
s2 = myReadFunc();
I get some odd results. The data is the same for both, and it is ALWAYS from the second specified read location.
So I tried some alternate code:
char * s1;
char * s2;
//Some code to specify where to read from.
char r [10];
//some code that reads data into r. IDENTICAL to myReadFunc().
s1 = r;
//Some code to change the read location.
s2 = myReadFunc();
This code produces results as I intended (s1
has data from one location, and s2
has data from another).
So, my question is, why did the latter code work, but the code above it did not? I my guess is that somehow my function was aliased to both variables, and since it was pointing to both, it reassigned both every single time it was called. Does anyone understand the full reason for this behavior?