I am trying to save a local variable from a function by storing it's address. However, it appears that the compiler is automatically freeing the memory of that variable, even after I store it's address into a pointer variable.
I am in a situation (not exactly like the code below) where I must have a class's member variable store the address of a variable declared in a function.
#include <stdio.h>
static int* p;
void foo(){
int a = 5;
p = &a;
}
int main(){
foo();
//some delay
printf("*p = %d\n",*p);
}
Ideally, *p
should be 5, but it ends up being a number that isn't 5, and it's different much of the times I rerun the script. I believe that the memory allocated to a
in foo
is being freed automatically. How can I make sure *p
is 5 despite any delay?