c++ - 在 u16 中转换 u8[] 时如何强制对齐错误?

标签 c++ c alignment

在回答问题时,我试图警告 OP 不要出现对齐问题。

但是当我做我的代码片段来向 OP 展示它是如何发生的时,我无法让它发生。

online compiler 上运行此代码 (C/C++) 时, 我预计它会失败

为什么不是呢?

#include <cstdint>
#include <cstddef>
#include <iostream>

#define SIZE 20
int main()
{
    uint8_t in[20];
    in[0] = 0;
    in[1] = 1;//8bit
    in[2] = 1;
    in[3] = 1;//16bit
    in[4] = 1;
    in[5] = 1;
    in[6] = 1;
    in[7] = 1;//32bit
    in[8] = 1;
    in[9] = 1;
    in[10] = 1;
    in[11] = 1;
    in[12] = 1;
    in[13] = 1;
    in[14] = 1;
    in[15] = 1;//64bit
    in[16] = 1;
    in[17] = 1;
    in[18] = 1;
    in[19] = 1;
    uint16_t out;

    for (int i =0; i < SIZE - 2; i++)
    {
        out = *((uint16_t*)&in[i+1]);
        std::cout <<  "&in: " << (void*)&in[i+1] <<  "\n out: " << out << "\n in: " << in[i+2]*256 + in[i+1]<< std::endl;
    }
    return 0;
}

最佳答案

When running this code, I would expect it to fail. Why is it not?

因为:

  1. 程序的行为未定义1。无法保证一定会失败2
  2. 您可能正在使用其 CPU 支持错位访问的系统。据我了解,例如 x86 执行未对齐的读写;它们只是比对齐的慢(尽管这不适用于 SIMD 指令)。

C++ 标准说(引用最新草案):

1

[basic.lval]

If a program attempts to access the stored value of an object through a glvalue whose type is not similar ([conv.qual]) to one of the following types the behavior is undefined:

  • the dynamic type of the object,
  • a type that is the signed or unsigned type corresponding to the dynamic type of the object, or
  • a char, unsigned char, or std::byte type.

uint16_t 不是在这种情况下列出的那些异常类型(好吧,它可能在某些具有 16 位字节的系统上,但通常不是,并且可能不在运行在线编译器的服务器上,这样的系统可能不会提供 uint8_t)。

2

[defns.undefined]

behavior for which this document imposes no requirements

请注意缺少任何保证。

关于c++ - 在 u16 中转换 u8[] 时如何强制对齐错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57201918/

相关文章:

c++ - 将算法 C++ 无效操作数替换为二进制表达式

c++ - 将 IP 数据包重定向到我的应用程序,然后将它们转发

c - 与 C 套接字的 2 路通信

html - IE7 css 帮助,为什么我的跨度不与我的内联图像垂直对齐?

css - 无法使用 HTML5/CSS 将文本居中

css - 无缝图像对齐,无论 CSS 的方向如何?

c# - 如何设计应从 C++ 和 C# 访问的组件

C++:类是否可以调用其成员变量的方法并将自身作为参数发送?

动态大小的多维数组的 C++ 解决方法

c - 打包多个值的二元运算