Search code examples
c++cfunctionmemorycall

C/C++ Memory Management for Functions


Suppose there is a one cpp file with global functions.

As far as i know instruction set is copy to memory when I run the program and stay there until program ends. Each time I called a function, virtual adresses of variables are same but I can't understand it allocates memory first and do not free until program ends or it allocates memory for each time I call function.

EDIT : I call functions in other functions than main, adresses are changed. So question is wrong. Sorry.


Solution

  • In typical implementations of C and C++ storage for local variables is allocated on the stack (see: Stack-based memory allocation) when the function is entered, and cleared from the stack when the function returns.

    That you have seen a function use the same address for its variables on different calls is actually a coincedence. Try nesting your function calls within other calls and see what happens:

    #include <stdio.h>
    
    int funcTwo()
    {
        int nn = 5;
        printf("funcTwo, &nn = %p\n", &nn);
    }
    
    int funcOne(int n)
    {
        int nn = n;
        printf("funcOne, &nn = %p\n", &nn);
        funcTwo();
    }
    
    int main(int argc, char **argv)
    {
        funcOne(5);
        funcTwo();
        return 0;
    }
    

    Sample output:

    funcOne, &nn = 0x7fff96726b7c
    funcTwo, &nn = 0x7fff96726b4c
    funcTwo, &nn = 0x7fff96726b7c
    

    Observe that &nn is slightly different inside the two calls to funcTwo. That's because one instance is called from inside funcOne, which has its own local variable on the stack (as well as its parameter, return address and any additional space used to save processor register values for example). The additional stack usage pushes the address of variables in funcTwo further up the stack (to a lower address, since the stack grows downwards on this architecture).