问题
Possible Duplicate:
Can a local variable's memory be accessed outside its scope?
I have the following code in C++
int* foo()
{
int myVar = 4;
int* ptr = &myVar;
return ptr;
}
int main()
{
printf("val= %d", *foo());
return 0;
}
The output i get is:
val = 4
So my question is since myVar is a local variable, shouldn't it be gone after the function returns? and shouldn't the pointer to it be a null pointer as well?
回答1:
So my question is since myVar is a local variable, should it be gone after the function returns?
Yes. It would point to the address you set it to. However, the region was local to the function. Assume it does not belong to you after what it points to goes out of scope.
It is as incorrect as:
uint8_t* p = (uint8_t*)malloc(count);
free(p);
p[0] = 1;
but far more difficult an error for your or your tools to diagnose because the region would exist on the stack (unless optimized away).
and shouldn't the pointer to it be a null pointer as well?
No. C and C++ don't manage this for you.
回答2:
In your case, printf("val= %d", *foo())
is printing the garbage value. As there is no other code, that data has not been changed.
You run this code, you will get the idea
int* foo()
{
int myVar = 4;
int* ptr = &myVar;
return ptr;
}
int* foo1()
{
int myVar = 5;
int* ptr = &myVar;
return ptr;
}
int main()
{
int* x = foo();
int* x1 = foo1();
printf("val= %d", *x);
return 0;
}
回答3:
The address at ptr* will remain allocated and if you call function again, it will change the pointer. At least that would be my theory. C++ will not overwrite your pointer for performance reasons.
int foo(int val) {
int myVar = val;
int* ptr = &myVar;
return ptr;
}
int main()
{
int *ptr = foo(4);
foo(3);
printf("val= %d", *ptr); //will print 3
return 0;
}
回答4:
The memory containing the address which held int myvar and any other local variables belonging to that function is unallocated the moment the function returns, however there is no cleanup procedure in C, so the value in memory will stay unaltered for that small moment between the return and printf accessing it.
Unallocating (or freeing, same thing) memory in C is like deleting a file in Windows, where the file contents are still on the drive for the time being, but will be overwritten any time that area is needed again for something else. You can still read the contents but you shouldn't trust what you read.
来源:https://stackoverflow.com/questions/10038470/pointer-to-local-variable-in-c