It is a common strategy in C to cast one type to another type, relying on the fact that the layout of a C struct has certain guarantees. Libraries such as GLib rely on this to implement object-oriented like inheritance. Basically:
struct Base
{
int x;
int y;
};
struct Derived
{
struct Base b;
int z;
};
This enables a Base*
pointer to be assigned to the address of a Derived
object.
But I'm also aware of the "strict aliasing" rule, which is the implicit assumption by the compiler that different-type pointers can't point to the same address. (This enables the compiler to perform certain optimizations.)
So, how are these two things reconciled? Many C libraries, include Glib, CPython, etc., use the above strategy to cast between types. Are they all simply compiling with flags like no-strict-aliasing
?
"Strict aliasing is an assumption, made by the C (or C++) compiler, that dereferencing pointers to objects of different types will never refer to the same memory location (i.e. alias each other.)"
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.
In C, C++, and some other programming languages, the term aliasing refers to a situation where two different expressions or symbols refer to the same object.
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.
There's no violation of strict aliasing in this case. struct Derived
contains a struct Base
. This sort of behaviour is explicitly allowed by the language standard. From C11 6.7.2.1 Structure and union specifiers, paragraph 15:
A pointer to a structure object, suitably converted, points to its initial member (or if that member is a bit-field, then to the unit in which it resides), and vice versa.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With