#include <stdio.h>
int main(void){
int a;
int b;
printf("%d %p %d %p", a, b, &a, &b);
return 0;
}
I have writen this C program trying to explore the memory allocation in C and i noticed something weird. I have run this program multiple times, around 50 and i noticed that the variable a is always getting the same adress, in my case 0000000000000010 while the address of variable b is always different. As i know every time you run a program the computer allocates memory for the variables of the program and the addresses allocated are not standard but change with each execution since they depend on the available memory. So how comes that variable a is allocated the same address every time but variable b gets a different address every time? Is this just a coinsidence or is there a particular reason that this is happening? Result of my experiment.
I was expecting to get different memory addresses allocated for both variable and since the program seems to allocate the same address to variable a but not to variable b it seemed weird to me.
You're mixing up the printing of the addresses of the variables and their contents.
You want this:
#include <stdio.h>
int main(void){
int a;
int b;
printf("%p %p", (void*)&a, (void*)&b);
return 0;
}
Anyway printing the values of a and b is meaningless, because they have not been initialized.
On the other hand printing the addresses of uninitialized variables is fine.
This version also prints the difference between the adresses of a
and b
.
Be aware that calculating the difference between the adresses of two different variables results in unspecified behaviour, here it is only done for demonstration purposes.
#include <stdio.h>
#include <stdint.h>
int main(void)
{
int a;
int b;
printf("%p %p\n", (void*)&a, (void*)&b);
printf("Difference: %d\n", (intptr_t)&a- (intptr_t)&b);
return 0;
}
You will usually get the same difference when you run the same program (compiled with the same compiler on the same platform) multiple times (typically 4, but other values are possible).