Memory aliasing

From Helpful
Jump to: navigation, search

Memory aliasing, closely related (arguably synonymous) to pointer aliasing, means that more than one variable name points to the same underlying stored value.

Since a compiler decides when to (re-)fetch memory contents, this has various effects on performance and correctness.


  • if multiple threads of execution access aliased memory, this amounts to shared memory
though if everything only reads, it's typically fine
Without some protocol or locking, this will probably go wrong
just how wrong also varies with compiler assumptions - see also the next point
  • When the compiler can not assume two things are not aliased, it must often fetch values more often.
in part because of variable reuse, and the possible case of different arguments to a function pointing to the same variable
  • When a compiler can / just does assume things are not aliased, it can assume the value it has is right.
Helps performance because of less memory access (mostly inner-loop stuff), and also because intrinsics apply more easily
Fortran compilers assume this, though code can violate it - so programmers should know not to
C does not assume this (its standard says so) until you tell it to.
Note that higher-level programs often make it harder to alias memory, primarily those that don't really use pointers
C has restrict, a property on a pointer that is the programmer promising that data written via it does not need to be read by another as soon as possible.(verify)
GPU code can also benefit. CUDA docs note that the combination of const and restrict can help.

C's aliasing rules (you'll probably have seen it referenced in compiler warnings) are mostly about situations that become ill defined, such as when casting pointers to an incompatible type (because the behaviour of dereferencing such incompatible pointers is undefined). . If you need this, consider using a union. Or perhaps look at the details of the exception case that is char *.

See also: