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

偶尔善良 提交于 2019-12-23 14:21:06

问题


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.


来源:https://stackoverflow.com/questions/39908946/unaligned-memory-access-is-it-defined-behavior-or-not

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!