Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to keep a pointer to a variable out of scope?

Tags:

c

pointers

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.

like image 565
kunigami Avatar asked Dec 27 '10 02:12

kunigami


People also ask

What happens to a pointer when it goes out of scope?

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.

What does it mean for a variable to go out of scope?

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.

How do you store a pointer in a variable?

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 * .

Can a variable be accessed outside of its scope?

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.


2 Answers

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.

like image 79
Merlyn Morgan-Graham Avatar answered Sep 18 '22 20:09

Merlyn Morgan-Graham


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.

like image 28
cdhowie Avatar answered Sep 18 '22 20:09

cdhowie