Example: pointer_offset_from_int_subtraction_auto_xy.c

up: index
prev: pointer_offset_from_int_subtraction_global_yx.c
next: pointer_offset_from_int_subtraction_auto_yx.c

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
    #include <stdio.h>
    #include <string.h> 
    #include <stdint.h>
    #include <inttypes.h>
    int main() {
      int x=1, y=2;
      uintptr_t ux = (uintptr_t)&x;
      uintptr_t uy = (uintptr_t)&y;
      uintptr_t offset = uy - ux;
      printf("Addresses: &x=%"PRIuPTR" &y=%"PRIuPTR\
             " offset=%"PRIuPTR" \n",(unsigned long)ux,(unsigned long)uy,(unsigned long)offset);
      int *p = (int *)(ux + offset);
      int *q = &y;
      if (memcmp(&p, &q, sizeof(p)) == 0) {
        *p = 11; // is this free of UB?
        printf("x=%d y=%d *p=%d *q=%d\n",x,y,*p,*q); 
      }
    }
[link to run test in Cerberus]

Experimental data (what does this mean?)

cerberus-concrete-PVI-plain Addresses: &x=4294962640 &y=4294962636 offset=18446744073709551612
x=1 y=11 *p=11 *q=11
cerberus-concrete-PVI-ae Addresses: &x=4294962640 &y=4294962636 offset=18446744073709551612
x=1 y=11 *p=11 *q=11
cerberus-concrete-PVI-ae-udi Addresses: &x=4294962640 &y=4294962636 offset=18446744073709551612
x=1 y=11 *p=11 *q=11
gcc-8.3-O0 Addresses: &x=140732920754900 &y=140732920754896 offset=18446744073709551612
x=1 y=11 *p=11 *q=11
gcc-8.3-O2 Addresses: &x=140732920754904 &y=140732920754908 offset=4
x=1 y=11 *p=11 *q=11
gcc-8.3-O3 Addresses: &x=140732920754904 &y=140732920754908 offset=4
x=1 y=11 *p=11 *q=11
gcc-8.3-O2-no-strict-aliasing Addresses: &x=140732920754840 &y=140732920754844 offset=4
x=1 y=11 *p=11 *q=11
gcc-8.3-O3-no-strict-aliasing Addresses: &x=140732920754840 &y=140732920754844 offset=4
x=1 y=11 *p=11 *q=11
clang-7.0.1-O0 Addresses: &x=140732920754904 &y=140732920754900 offset=18446744073709551612
x=1 y=11 *p=11 *q=11
clang-7.0.1-O2 Addresses: &x=140732920754904 &y=140732920754908 offset=4
x=1 y=11 *p=11 *q=11
clang-7.0.1-O3 Addresses: &x=140732920754904 &y=140732920754908 offset=4
x=1 y=11 *p=11 *q=11
clang-7.0.1-O2-no-strict-aliasing Addresses: &x=140732920754856 &y=140732920754860 offset=4
x=1 y=11 *p=11 *q=11
clang-7.0.1-O3-no-strict-aliasing Addresses: &x=140732920754856 &y=140732920754860 offset=4
x=1 y=11 *p=11 *q=11
icc-19-O0 Addresses: &x=140737488348784 &y=140737488348788 offset=4
x=1 y=11 *p=11 *q=11
icc-19-O2 Addresses: &x=6309568 &y=6309572 offset=4
x=1 y=11 *p=11 *q=11
icc-19-O3 Addresses: &x=6309568 &y=6309572 offset=4
x=1 y=11 *p=11 *q=11
icc-19-O2-no-strict-aliasing Addresses: &x=6309568 &y=6309572 offset=4
x=1 y=11 *p=11 *q=11
icc-19-O3-no-strict-aliasing Addresses: &x=6309568 &y=6309572 offset=4
x=1 y=11 *p=11 *q=11