Example code:
#include <stdio.h>
int main (){
int *p;
{
int v = 1;
p = &v;
}
printf("%d\n", *p);
return 0;
}
This code works fine, but I'm not sure if there's a guarantee that the address of v will be preserved.
If a pointer goes out of scope or its parent object is deleted, the object that the pointer references still exists in memory. Thus the rule of thumb that any code that allocates ( news ) an object owns the object and should also delete that object when it's no longer needed.
A variable declared within a block of code has local scope, and is only accessible by other code within the same block. Once the block within which it is declared is exited, the variable goes out of scope.
To store the address of int variable var , we have the pointer to int ptr_var . We would need another pointer to store the address of ptr_var . Since ptr_var is of type int * , to store its address we would have to create a pointer to int * .
The var keyword is limited to function scope, meaning that new scope can only be created inside functions. Function and block scopes can be nested. In such a situation, with multiple nested scopes, a variable is accessible within its own scope or from inner scope. But outside of its scope, the variable is inaccessible.
There is no guarantee.
Once v
goes out of scope, doing anything with it at all (even via a pointer) is considered Undefined Behavior.
As with any other undefined behavior, just because it works on one operating system, compiler, compiler version, time of day, etc, doesn't mean it will work for another.
To add on Merlyn's answer, one case where this would probably result in behavior you didn't intend is the following:
#include <stdio.h>
int main (){
int *p;
{
int v = 1;
p = &v;
}
{
int w = 2;
printf("%d\n", w);
}
printf("%d\n", *p);
return 0;
}
The compiler may optimize this by having v
and w
share the same allocation on the stack. Again, the compiler might also not optimize this -- that's why the behavior of using pointers to variables after their enclosing block ends isn't defined. The program might output "2" and "1", or "2" and "2", or "2" and something completely different depending on which compiler and settings are used.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With