简体   繁体   中英

C, what happens with the variables of a function when it finish?

Supposing the following code:

void foo()
{
    int i = 5;
    printf("%d", i);
}

int main()
{
    foo();

    return 0;
}

When I call foo, "i" is declared and set to 5, when this function finish, the "i" variable is released?

Can I call the foo() in a while(1) loop without memory leak risk?

Thanks!

In C language, variables have a scope, an area of your code they belong to, like a loop or a function. In this case, the scope of your variable is your function.

When the end of the scope of your variable is reached, your variable is deallocated. This means the memory used by your variable is released. So at the end of your function, the only memory space you allocated (the one you used to store an integer) is released.

To continue on the general question in the title, you can also allocate memory that will persist outside the scope of your declaration.

void foo()
{
    int i = 5;
    int* j = (int*) malloc(sizeof(int));
    *j = i*2
    printf("%d", i);
}

For example, in the code above, both the i and j variable will be deallocated at the end of the function.

However, j is a pointer, and it is the memory space containing the pointer that will be deallocated, not the memory space containing the actual value pointed by j (and this would be true even without allocating a value to *j).

To avoid a memory leak here, you would have to call free(j) before exiting your function.

If the function were returning an int* instead of being of type void , you could also return j instead of freeing it, so you would still have access to the memory area pointed by j where you called this function. Doing so, you would be able to use the value and later deallocate the memory space used by calling free(j); .

int i = 5;

Declares a variable of int type on the stack. Variables declared on the stack free their memory when they go out of scope. i goes out of scope when the function is finished.

So yes, you can call that function over and over with no memory leak.

You should not care, and you should believe that i vanishes. In all implementations I know about, that local i either was in a register which becomes reused for other purposes, or was in a stack frame which got popped. See eg the wikipage on call stacks which gives a nice picture.

AFAIU, nothing in the C99 standard specification exactly requires a stack, but I know no implementation which don't use any stack.

So of course, you can call foo in a loop within main .

I suggest to compile your code with all warnings and debug info (eg gcc -Wall -g ) and to use the debugger (eg gdb ) to run your program step by step and display the address of i

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM