未对齐的内存访问:它是定义的行为还是不行? [英] Unaligned memory access: is it defined behavior or not?

查看:146
本文介绍了未对齐的内存访问:它是定义的行为还是不行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码:

#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; 违反严格别名规则会导致未定义的行为。 * u 是类型 unsigned long long 的左值,严格别名规则表示这只能用于访问对象(已存在)并具有类型 long long unsigned long long 。但是,您的代码使用它来访问 char 的数组。

*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 ++没有对齐的特定规则访问(不同于C)。这是因为在C ++中,不可能编写执行未对齐访问的代码,而不会由于以下某种原因导致未定义的行为:

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:



  • 向placement-new提供未对齐的地址

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

这篇关于未对齐的内存访问:它是定义的行为还是不行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆