Static Variable
Normally, stack memory address will be destroyed:
Stack memory
Normally, local variables will be stored in stack memory and will be destroyed after there is no reference to that local variables anymore
This will happen especially in the functions
int* stackMemoryAddress() {
int myNumber { 10 };
return &myNumber;
}
or
int* stackMemoryAddress() {
int myNumber { 10 };
int *ptr = &myNumber;
return ptr;
}
cout << *stackMemoryAddress() << endl;
Note that in here the myNumber
will be destroyed and the program might crash. However, sometimes it might works.
There are 2 options to fix this
Static variables
int* stackMemoryAddress() {
static int myNumber { 10 };
return &myNumber;
}
cout << *stackMemoryAddress() << endl;
Doing this would move the variable to the heap space instead of stack
Malloc this variables
Another option is to malloc this, this will in turn store this variable in heap
int* stackMemoryAddress() {
int myNumber { 10 };
int *ptr = (int*) malloc(sizeof(myNumber));
ptr = &myNumber;
return ptr;
}
cout << *stackMemoryAddress() << endl;