I am trying to print the distance between two pointers, but I have found that sometimes the code doesn't work well.
#include <stdio.h>
#include <math.h>
/**
* Print the distance between 2 pointers
*/
void distance(int * a0, int * a1){
size_t difference = (size_t) a1 - (size_t) a0;
printf("distance between %p & %p: %u\n" ,a0, a1, abs((int) difference));
}
Trying this works perfectly!!
int main(void){
int x = 100;
int y = 3000;
distance(&x, &y);
return 0;
}
printing (example):
distance between 0028ff18 & 0028ff14: 4
But start to going wrong with this code
int main(void){
int x = 100;
int p = 1500;
int y = 3000;
distance(&x, &y);
p = p + 2; // remove unused warning
// &p
return 0;
}
printing (example):
distance between 0028ff18 & 0028ff14: 4
When it has to print 8
because of an integer separating this values!
But if I uncomment //&p
, it works again.
It is as if the variable p
does not exist until its memory address is used.
I'm using gcc 4.9.3 on windows 7 (64 bits)
p
is not used in your program and is likely to be optimized out. Anyway this is implementation details and the compiler is free to even change the order of the x
and y
objects in memory.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With