Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why do i get the same value of the address?

Tags:

c

#include<stdio.h>
#include<conio.h>

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

int main()
{
    vaibhav();
    vaibhav();
    vaibhav();
    getch();
    return 0;
} 

Every time I get the same value for the address of variable a.

Is this compiler dependent? I am using dev c++ ide.

like image 680
user2738777 Avatar asked Feb 17 '14 18:02

user2738777


2 Answers

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);
like image 24
haccks Avatar answered Oct 08 '22 21:10

haccks


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.

like image 198
barak manos Avatar answered Oct 08 '22 22:10

barak manos