Below is the code
The Code:
#include <stdio.h>
int * num(void);
int main(void)
{
int * num2;
num2 =num();
printf("%d\n" , *num2);
return 0;
}
int * num(void)
{
int num = 20;
return #
}
The Question :
-
As we know , the function
numis local to its functionnum(), so in this code I try to return the address of the variablenumin the function to the function that calls it , which ismain(). -
After that I just use the dereferencing operator to extract the value of the specific
numvariable and print it out inmain()function. -
There’s one thing i’m confused . I remember i read a book about javascript that mention a variable lifetime is within the function , which mean after the function finish performing its instructions and pass the control back to the function that calls it , the value of each variable in the function will be clean out(garbage collector).But why in this code my
main()function still can point to the value of that specific memory address??
The reason you can see the value of the variable is because of how the stack works. Effectively as you enter the function
num, a pointer (the stack pointer) is moved to add space in for the local storage of the function. When you exit the function the stack pointer is moved back effectively meaning that the next function call will overwrite the stack storage used in the previous function call. Until it is overwritten, however, the value exists in a sort of limbo. It’s still actually there in memory but may get overwritten at any moment. The existence of the actual value there may or may not be the case. That is why doing as you do above is known as undefined behaviour.Basically … don’t do it.