why do i get the same value of the address?

后端 未结 4 1743
无人共我
无人共我 2020-12-11 07:13
#include
#include

void vaibhav()
{
    int a;
    printf(\"%u\\n\",&a);
}

int main()
{
    vaibhav();
    vaibhav();
    vaibhav(         


        
相关标签:
4条回答
  • 2020-12-11 07:35

    It is not necessary. You may or may not get the same value of the address. And use %p instead.

     printf("%p\n", (void *)&a);
    
    0 讨论(0)
  • 2020-12-11 07:40

    Try to call it from within different stack depths, and you'll get different addresses:

    void func_which_calls_vaibhav()
    {
        vaibhav();
    }
    
    int main()
    {
        vaibhav();
        func_which_calls_vaibhav();
        return 0;
    }
    

    The address of a local variable in a function depends on the state of the stack (the value of the SP register) at the point in execution when the function is called.

    In your example, the state of the stack is simply identical each time function vaibhav is called.

    0 讨论(0)
  • 2020-12-11 07:43

    "a" in the function vaibhav() is an automatic variable, which means it's auto-created in the stack once this fun is called, and auto-released(invalid to the process) once the fun is returned. When funA(here is main) calls another funB(here is vaibhav), a stack frame of funB will be allocated for funB. When funB returns, stack frame for funB is released.

    In this case, the stack for funB(vaibhav) is called 3 times sequentially, exactly one by one. In each call, the stack frame for funB is allocated and released. Then re-allocated and recycled for times.

    The same memory block in stack memory is re-used for 3 times. In that block, the exact memory for "a" is also re-used for 3 times. Thus, the same memory and you get the same address of it.

    This is definitely compiler dependent. It depends on the compiler implementation. But I believe almost every C compiler will produce the same result, though I bet there is no specific requirement in C standard to define the expected output for this case.

    0 讨论(0)
  • 2020-12-11 07:48

    You should use %p format specifier to print address of a variable. %u & %d are used to display integer values. And the address on stack can be same or not every time you call function vaibhav().

    0 讨论(0)
提交回复
热议问题