> On Sun, 2024-01-28 at 21:33 -0800, Yonghong Song wrote: > [...] >> I tried below example with the above prog/dynptr_fail.c case with gcc 11.4 >> for native x86 target and didn't trigger the warning. Maybe this requires >> latest gcc? Or test C file is not sufficient enough to trigger the warning? >> >> [~/tmp1]$ cat t.c >> struct t { >> char a; >> short b; >> int c; >> }; >> void init(struct t *); >> long foo() { >> struct t dummy; >> init(&dummy); >> return *(int *)&dummy; >> } >> [~/tmp1]$ gcc -Wall -Werror -O2 -g -Wno-compare-distinct-pointer-types -c t.c >> [~/tmp1]$ gcc --version >> gcc (GCC) 11.4.1 20230605 (Red Hat 11.4.1-2) > > I managed to trigger this warning for gcc 13.2.1: > > $ gcc -fstrict-aliasing -Wstrict-aliasing=1 -c test-punning.c -o /dev/null > test-punning.c: In function ‘foo’: > test-punning.c:10:19: warning: dereferencing type-punned pointer might break strict-aliasing rules [-Wstrict-aliasing] > 10 | return *(int *)&dummy; > | ^~~~~~ > > Note the -Wstrict-aliasing=1 option, w/o =1 suffix it does not trigger. > > Grepping words "strict-aliasing", "strictaliasing", "strict_aliasing" > through clang code-base does not show any diagnostic related tests or > detection logic. It appears to me clang does not warn about strict > aliasing violations at all and -Wstrict-aliasing=* are just stubs at > the moment. Detecting strict aliasing violations can only be done by looking at particular code constructions (casts immediately followed by dereferencing for example) so GCC provides these three levels: 1, 2, and 3 which is the default. Level 1 can result in false positives (hence the "might" in the warning message) while higher levels have less false positives, but will likely miss lots of real positives. In this case, it seems to me clear that a pointer to int does not alias a pointer to struct t. So I would say, in this little program strict-aliasing=1 catches a real positive, while strict-aliasing=3 misses a real positive.