The C standard says that accessing a value of one type through a pointer of a 
different type (except char) is undefined behavior (note: the actual semantics 
are a bit more involved, this is the ELI15 version).

So, if there's pointer casting going on under the hood, sufficiently aggressive 
optimization can lead to undefined behavior. This is a potential problem 
especially for a lot of memory allocators (not just in Nim), which do that kind 
of stuff a lot (the official way to do it in a defined way is to use a pointer 
to a union).

The reason why compilers are increasingly making use of it is that it gives 
them some guarantees about aliasing (or rather, lack thereof), which provides 
additional optimization opportunities. The problem is that a lot of code hasn't 
actually been written with these assumptions in mind.

Note that _undefined_ behavior in the C/C++ standards is different from 
_unspecified_ or _implementation-defined_ behavior. Implementation-defined and 
unspecified behavior is still assumed to have some semantics, just not 
something that you can rely on (such as the value of `sizeof(int)`). Undefined 
behavior has been increasingly exploited by compiler writers to mean "this 
cannot happen" and create code based on the assumption that this is an 
impossibility. This is an issue both for people who write C/C++ code manually 
and for compilers that emit C/C++ code.

Reply via email to