更新时间:2023-11-14 22:51:40
glibc
文档相当清楚地表明您应该在哪里使用aligned_alloc
:
在GNU系统中,由
malloc
或realloc
返回的块的地址始终为8的倍数(在64位系统上为16).如果您需要一个块的地址是其高2的幂的倍数,请使用aligned_alloc
或posix_memalign
.
The address of a block returned by
malloc
orrealloc
in GNU systems is always a multiple of eight (or sixteen on 64-bit systems). If you need a block whose address is a multiple of a higher power of two than that, usealigned_alloc
orposix_memalign
.
C标准已经保证malloc
将为任何标准类型返回适当对齐的内存块,但是在某些情况下,您可能需要或需要更严格的对齐方式.
The C standard already guarantees that malloc
will return a suitably aligned memory block for any of the standard types but there may be situations in which you want or need stricter alignment.
作为一个例子,我似乎想起了SSE2(SIMD)指令需要将其数据对齐在16个字节的边界上,因此即使在malloc
仅保证与8对齐的系统上,您也可以使用aligned_alloc
为您提供数据字节边界.
As one example, I seem to recall that SSE2 (SIMD) instructions need their data aligned on 16-byte boundaries so you could use aligned_alloc
to give you that even on systems where malloc
only guarantees alignment to an 8-byte boundary.