c - Does accessing an array of uint32_t with an uint16_t* lead to undefined behavior? -
i have following ostensibly simple c program:
#include <stdint.h> #include <stdio.h> uint16_t foo(uint16_t *arr) { unsigned int i; uint16_t sum = 0; (i = 0; < 4; i++) { sum += *arr; arr++; } return sum; } int main() { uint32_t arr[] = {5, 6, 7, 8}; printf("sum: %x\n", foo((uint16_t*)arr)); return 0; }
the idea being iterate on array , add it's 16-bit words ignoring overflow. when compiling code on x86-64 gcc , no optimization seem correct result of 0xb (11) because it's summing first 4 16-bit words include 5, , 6:
$ gcc -o0 -o castit castit.c $ ./castit sum: b $ ./castit sum: b $
with optimization on it's story:
$ gcc -o2 -o castit castit.c $ ./castit sum: 5577 $ ./castit sum: c576 $ ./castit sum: 1de6
the program generates indeterminate values sum.
i'm assuming position it's not compiler bug now, lead me believe there undefined behavior in program, can't point specific thing lead it.
note when function foo compiled separately linked module issue not seen.
you breaking strict aliasing rule, indeed ub. that's because alias array arr
of uint32_t
via pointer of different type, i.e. uint16_t
when passing foo(uint16_t*)
.
the pointer type can use alias other types char*
.
some additional reading material on subject: http://dbp-consulting.com/tutorials/strictaliasing.html
Comments
Post a Comment