Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Visual C++ support "strict aliasing"?

I recently was surprised to learn that the C and C++ language standards have a "strict aliasing" rule. In essence, the rule prohibits variables of differing types from referencing the same memory location.

As an example:

char buffer[4] = { 0x55, 0x66, 0x77, 0x88 };
int32 *p = (int32*)&buffer[0]; // illegal because buffer[0] and *p are different types

Most of the professional C++ developers I interact with are not familiar with this rule. Based on my research, it seems to affect mostly GCC/G++/CLANG users. Does Visual C++ support enabling/disabling this rule? If so, how does one do so?

Thank you

like image 673
digitale Avatar asked May 12 '16 02:05

digitale


People also ask

Does C have strict aliasing?

One of the lesser-known secrets of the C programming language is the so-called “strict aliasing rule”. This is a shame, because failing to adhere to it takes you (along with your code) straight into the realm of undefined behavior.

Why is aliasing strict?

This is done because they referred to the same memory location. Strict Aliasing: GCC compiler makes an assumption that pointers of different types will never point to the same memory location i.e., alias of each other. Strict aliasing rule helps the compiler to optimize the code.

Does Visual Studio have C Support?

Visual Studio Code is a lightweight, cross-platform development environment that runs on Windows, Mac, and Linux systems. The Microsoft C/C++ for Visual Studio Code extension supports IntelliSense, debugging, code formatting, auto-completion. Visual Studio for Mac doesn't support Microsoft C++, but does support .

What is the problem of aliasing while using pointers?

Two seemingly different pointers may point to storage locations in the same array (aliasing). As a result, data dependencies can arise when performing loop-based computations using pointers, as the pointers may potentially point to overlapping regions in memory.


1 Answers

"Strict aliasing" is a C++ rule restricting programs, not compilers. Since violating the rule is Undefined Behavior, no diagnostic required a compiler doesn't need to support it in any way.

That said, Microsoft is a bit less aggressive in applying optimizations. Only last week have they announced their new optimizer assumes no signed overflow, something that GCC has assumed for a few years already. Strict aliasing is going to break a few Windows headers, so those need fixing first. (A few types act as if they contain unions, but they're not formally defined as such)

like image 174
MSalters Avatar answered Oct 13 '22 09:10

MSalters