-->

Unaligned memory access: is it defined behavior or

2019-06-26 08:55发布

问题:

This question already has an answer here:

  • What does the standard say about unaligned memory access? 1 answer

Consider the following code:

#include <iostream>

int main()
{
    char* c = new char('a');
    char ac[4] = {'a', 'b', 'c', 'd'};
    unsigned long long int* u = reinterpret_cast<unsigned long long int*>(c);
    unsigned long long int* uc = reinterpret_cast<unsigned long long int*>(&ac[3]);
    *u = 42;
    *uc = 42;
    std::cout<<*u<<" "<<*uc<<std::endl;
}

Is this considered as a valid code, or is it memory leak/undefined behaviour? I am asking, because through:

*u = 42;
*uc = 42;

we are accessing bytes that should not be reachable by the program (I guess).

回答1:

*u = 42; causes undefined behaviour by violating the strict aliasing rule. *u is an lvalue of type unsigned long long, and the strict aliasing rule says that this may only be used to access objects (that already exist) and have type long long or unsigned long long. However your code uses it to access an array of char.

C++ doesn't have a specific rule for aligned accesses (unlike C). This is because in C++ it's not possible to write code that would perform an unaligned access without causing undefined behaviour due to one of the following things:

  • violating the strict aliasing rule.
  • accessing memory where no object exists.
  • supplying an unaligned address to placement-new.