Shelef
Shelef

Reputation: 3827

Is it possible to keep a pointer to a local variable beyond that variable's scope?

Suppose that I use this code:

int *pointer;
if(1) {
    int num = 5; // local variable, can't be used outside the if block.
    pointer = &num
}

Is this a safe way to keep track of the num variable? I know this code will work. But I think the compiler will use the old num memory to allocate new variables, causing pointer to refer to an unpredictable value. Is that true?

Upvotes: 2

Views: 129

Answers (2)

bash.d
bash.d

Reputation: 13207

No, it probably won't work, as you a trying to keep the value of an object that goes out of scope and the stack frame it belongs to will be destroyed. This might work once or twice, but it is always undefined behavior.

Upvotes: 1

Daniel Fischer
Daniel Fischer

Reputation: 183968

No, it's not safe. When the closing } of the if is reached, num's lifetime ends, and the value of pointer becomes indeterminate. Using it thereafter invokes undefined behaviour.

What the compiler actually does depends, it may well use the storage that is used for num for another local variable that is not used before num comes into existence. Then using pointer to obtain the value that num had would definitely fail.

Upvotes: 11

Related Questions