Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
186 views
in Technique[技术] by (71.8m points)

c - Why did gcc stop warning about strict aliasing violation from version 7.2?

If I compile this code up to gcc 7.1 with -O2 -Wall (or -O3)

#include <stdio.h>

int main (void)
{
  char array [4] = {0x11,0x22,0x33,0x44};
  unsigned int u32 = *(unsigned int*)array; // intentionally invoking strict aliasing UB here
  printf("%x
", u32);
  return 0;
}

Godbolt

Then I get I diagnostic about the undefined behavior:

warning: dereferencing type-punned pointer will break strict-aliasing rules [-Wstrict-aliasing]

This only happens when optimizations are enabled.

In 7.2 this warning disappeared and remains disabled to this day. What happened in 7.2 that made the warning go away? As usual with gcc, the change is completely undocumented - https://gcc.gnu.org/gcc-7/changes.html doesn't say a thing about changes to strict aliasing. Compiling with or without -fstrict-aliasing doesn't seem to matter either.

Was the behavior in 7.2 changed on purpose or is this a bug? Are there any known bug reports?

question from:https://stackoverflow.com/questions/65842647/why-did-gcc-stop-warning-about-strict-aliasing-violation-from-version-7-2

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think gcc's warning logic is treating accesses to a top-level character array via pointers of other types as though it were Standard-defined behavior, even though the Standard does not require such treatment, and even though gcc does not treat pointers which are formed by directly indexing such an array likewise. Change the type of the array to something other than a character type and gcc will squawk. Add a value which gcc cannot recognize as a constant (e.g. write a zero to a volatile object and read it back) to the address and gcc won't squawk with any array type, but won't reliably generate meaningful code either.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...