Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

compatible types vs. strict aliasing rules

Tags:

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?

like image 456
Channel72 Avatar asked Sep 25 '13 16:09

Channel72


People also ask

What is the strict aliasing rule and why do we care?

"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.)"

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.

What is C++ aliasing?

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.

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

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.

like image 129
Carl Norum Avatar answered Sep 27 '22 02:09

Carl Norum