如何对齐但偏移
假设我需要分配struct a
,但是b
需要对4对齐。
struct A
{
char a;
char b[42];
};
我想我可以通过malloc()
手动填充指针。有什么清洁的方式吗?像GCC的__属性__(((对齐(4))))
,但这与整个结构保持一致。而且我无法更改它是布局。
Say I need to allocate struct A
but b
needs to be 4 aligned.
struct A
{
char a;
char b[42];
};
I guess I can manually pad a pointer returned by malloc()
. Any cleaner way? Like gcc's __attribute__((aligned(4)))
but that aligns the whole structure. And I can't change it's layout.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以在要对齐的结构成员上使用
alignas(< Alignment>)
。这意味着struct
和Union
类型将获得等于任何成员的最大对齐的对齐,并将在元素(和数组条目)之间插入填充物,以确保必要的提供对齐方式。对于编译器分配的数据(静态或堆栈),这就是您需要做的。
对于C11,对于任何动态分配的数据,您仍然需要确保分配的基本指针适当对齐 - Malloc不能保证“对于最长的天然类型的足够”。在您的情况下,使用
alignas(4)
malloc可能适合最长的天然类型,因此malloc可以,但是在一般情况下,如果过度对齐,则可能需要手动计算的填充(例如,SIMD矢量为Simd vector负载)。如果您需要对此的标准支持,则需要快速前向C ++ 17,这添加了许多以对齐为参数的内存分配器。这些分配器专门用于过度对准类型。此外,C ++ 17保证了
新
的任何分配都足够对齐Alignof(std :: max_align_t)
默认情况下。You can use
alignas(<alignment>)
on the structure member you want to align. This implies thatstruct
andunion
types will get an alignment equal to the largest alignment of any member, and will insert padding between elements (and array entries) to ensure that the necessary alignment is provided.For compiler-allocated data (static or stack) this is all you need to do.
For C11, for any dynamically allocated data you still need to ensure that the base pointer of the allocation is suitably aligned - malloc doesn't guarantee much more than "enough for the longest native type". In your case with
alignas(4)
malloc would likely fit in the longest native type so malloc would be OK, but in the general case you might need manually calculated padding if over-aligning (e.g. for SIMD vector loads).If you want standard support for this you need to fast-forward to C++17, which adds a number of memory allocators that take alignment as a parameter. These allocators are used specifically for over-aligned types. Also C++17 guarantees any allocations from
new
are sufficiently aligned foralignof(std::max_align_t)
by default.使用标准C,您可以使用关键字
_ALIGNAS
(或stdalign.h
> satdalign.h )的宏alignas
):因此,这使得
a 占用4个字节和
b
44个字节。示例:输出:
With standard C you can use the keyword
_Alignas
(or the macroalignas
fromstdalign.h
):This consequently makes
a
occupy 4 bytes andb
44 bytes. Example:Output: