【问题标题】:memory alignment higher than maximum alignment alignas malloc内存对齐高于最大对齐 alignas malloc
【发布时间】:2017-06-27 17:30:25
【问题描述】:

如何使用 malloc(或 new,因为在大多数实现中,new 是用 malloc 实现的,不确定标准对对齐和 new 的规定是什么,除了数据必须与最高标量对齐对齐)与类型将对齐要求设置为高于系统上的最大对齐要求 (alignof(std::max_align_t))?所以像

alignas(alignof(std::max_align_t) + alignof(int)) struct Something {
    ...
};

【问题讨论】:

  • n 表示所需的对齐方式(很遗憾,您在问题中没有提到这一点;本来可以更容易地回答它)。只需用n+sizeof(struct Something) 调用malloc,然后从malloc 返回的值开始搜索对齐的地址。保证您在[retVal,retVal+n-1] 之间找到这样的有效地址。然后将其用作结构的基地址。
  • @barakmanos 这是一个聪明的黑客哈哈,没有图书馆解决方案吗?我猜 C 不必担心这一点,因为没有比最大标量要求更高的对齐要求
  • 我相信任何厂商都必须提供适合所支持平台(编译器+底层硬件架构)的malloc
  • 使用 C++11,您可以使用aligned_alloc。如果没有 C++11,在 Visual Studio 中您可以使用 _aligned_malloc(但它更多的是 C 而不是 C++)。

标签: c++ alignment malloc alignas


【解决方案1】:

将评论变成答案。

ALIGNMENT 表示所需的对齐方式。

然后你可以安全地分配你的结构如下:

char* buffer = new char[ALIGNMENT+sizeof(Something)];
uintptr_t address = reinterpret_cast<uintptr_t>(buffer);
uintptr_t aligned_address = address+ALIGNMENT-address%ALIGNMENT;
Something* something = reinterpret_cast<Something*>(aligned_address);

【讨论】:

    猜你喜欢
    • 2018-07-22
    • 2013-06-10
    • 1970-01-01
    • 2013-06-27
    • 1970-01-01
    • 2018-09-01
    • 2016-02-12
    • 2015-05-19
    • 2015-03-22
    相关资源
    最近更新 更多