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).
*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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With