Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Distance between arbitrary pointers

Tags:

c

memory

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)

like image 933
Jorgito Avatar asked Dec 24 '22 15:12

Jorgito


1 Answers

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.

like image 168
ouah Avatar answered Dec 27 '22 04:12

ouah