When will memory used in a function become free ??(C programming)

拈花ヽ惹草 提交于 2019-12-04 21:06:21
Goz

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 &num;
}

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!