kunigami
kunigami

Reputation: 3086

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

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.

Upvotes: 14

Views: 2429

Answers (3)

Sree Ram
Sree Ram

Reputation: 859

ya it will work sometimes but one cannot be sure that it works ...It sometimes not only causes bus error but even can cause the whole program crash ...

i will give u an example

take a look at this .. http://www.functionx.com/cpp/examples/returnreference.htm

here he is trying to return the reference of a variable which goes out of scope ...(Big blunder) ..but it works ....

u cant guarantee ..So its better (not better best ) never to return reference to data that goes out of scope

Upvotes: 0

cdhowie
cdhowie

Reputation: 169231

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.

Upvotes: 8

Merlyn Morgan-Graham
Merlyn Morgan-Graham

Reputation: 59131

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.

Upvotes: 27

Related Questions