When will memory used in a function become free ??(C programming)
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
num
is local to its functionnum()
, so in this code I try to return the address of the variablenum
in 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
num
va开发者_开发技巧riable 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.
Just adding to what @Goz has very well explained. Try this code:
#include <stdio.h>
int * num(void);
int fib(int n)
{
if( 0 == n || 1 == n )
return n;
return fib(n-1) + fib(n-2);
}
int main(void)
{
int * num2;
num2 =num();
(void)fib(7);
printf("%d\n" , *num2);
return 0;
}
int * num(void)
{
int num = 20;
return #
}
There is very good chance that you will not get "20" as the output (There is a chance of program termination as well) Also when you are compiling the compiler does warn you about this "warning: function returns address of local variable" :)
Returning a pointer to a local variable is not right. The variable num
is deallocated when that function returns and that memory address is free to be used by the C runtime for another value. The pointer returned is now invalid, because it's pointing to an unallocated region of memory, and will invoke undefined behaviour if used. Undefined behaviour means it may or may not do what you want. In some cases the program will crash, in other case it may work. Why it works in this case is because that part of memory will still hold the value 20
. The C runtime doesn't fill that part of memory with 0's after deallocation.
精彩评论