"Felix J. Ogris" <fjo-lists@xxxxxxxx> writes: > maybe someone can enlighten me? Given a small test.c: > > #include <stdio.h> > > int chksum(void *ptr, unsigned int len) { > int sum = 0; > short *val = ptr; > > for (; len >= sizeof(short); len -= sizeof(short)) { > sum += *val; > val++; > } > > return sum; > } > > int main() { > struct s { > int a; > int b; > } s; > > s.a = 2; > s.b = 1; > s.a = chksum(&s, sizeof(struct s)); > > printf("%i\n", s.a); > > return 0; > } > > > Expected output: 3 > Compiled using `gcc -W -Wall -O3 -o test test.c` with gcc 4.1.2 on CentOS 5.4 x86_64 or with gcc 4.2.1 on FreeBSD 8.2 i386 gives random rubbish instead, eg. -16897 > Compiled with -O2 or -fno-strict-aliasing or -fno-inline-functions gives expected output. > > Is there anything I could do against this (mis-)behaviour - except using one the above flags or using a union as *val which contains two shorts? Is there any -Warning parameter for this? This code is accessing values of type int using a pointer of type short*. That is invalid aliasing and your program uses undefined behaviour. Your suggested workarounds are the right one. To get a warning, you could try the -Wstrict-aliasing option. I don't think it exists in gcc 4.2, though. Ian