Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unaligned memory access: is it defined behavior or not? [duplicate]

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

like image 254
Vincent Avatar asked Oct 07 '16 03:10

Vincent


1 Answers

*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.
like image 74
M.M Avatar answered Sep 27 '22 22:09

M.M