_aligned_malloc
分配在指定的对齐边界的内存。
void * _aligned_malloc(
size_t size,
size_t alignment
);
参数
size
请求的内存分配的大小。alignment
对齐值,则必须是整数幂的 2。
返回值
对分配或 NULL 的指针内存块,如果操作失败。 指针是 alignment的多个。
备注
_aligned_malloc 基于 malloc。
_aligned_malloc 标记为 __declspec(noalias) 和 __declspec(restrict),这意味着函数保证不修改全局变量,返回的指针没有抗锯齿。 有关更多信息,请参见 noalias 和 限制。
此功能设置 errno 到 ENOMEM ,如果内存分配失败或,如果请求的大小大于 _HEAP_MAXREQ大。 有关 errno的更多信息,请参见errno、_doserrno、_sys_errlist和_sys_nerr。 此外, _aligned_malloc 验证其参数。 如果 alignment 不是 2 的次幂或 size 为零,此函数调用的参数无效处理程序,如 参数验证所述。 如果执行允许继续,此函数返回 NULL 并将 errno 到 EINVAL。
要求
实例 |
必需的头 |
---|---|
_aligned_malloc |
malloc.h |
示例
// crt_aligned_malloc.c
#include <malloc.h>
#include <stdio.h>
int main() {
void *ptr;
size_t alignment,
off_set;
// Note alignment should be 2^N where N is any positive int.
alignment = 16;
off_set = 5;
// Using _aligned_malloc
ptr = _aligned_malloc(100, alignment);
if (ptr == NULL)
{
printf_s( "Error allocation aligned memory.");
return -1;
}
if (((int)ptr % alignment ) == 0)
printf_s( "This pointer, %d, is aligned on %d\n",
ptr, alignment);
else
printf_s( "This pointer, %d, is not aligned on %d\n",
ptr, alignment);
// Using _aligned_realloc
ptr = _aligned_realloc(ptr, 200, alignment);
if ( ((int)ptr % alignment ) == 0)
printf_s( "This pointer, %d, is aligned on %d\n",
ptr, alignment);
else
printf_s( "This pointer, %d, is not aligned on %d\n",
ptr, alignment);
_aligned_free(ptr);
// Using _aligned_offset_malloc
ptr = _aligned_offset_malloc(200, alignment, off_set);
if (ptr == NULL)
{
printf_s( "Error allocation aligned offset memory.");
return -1;
}
if ( ( (((int)ptr) + off_set) % alignment ) == 0)
printf_s( "This pointer, %d, is offset by %d on alignment of %d\n",
ptr, off_set, alignment);
else
printf_s( "This pointer, %d, does not satisfy offset %d "
"and alignment %d\n",ptr, off_set, alignment);
// Using _aligned_offset_realloc
ptr = _aligned_offset_realloc(ptr, 200, alignment, off_set);
if (ptr == NULL)
{
printf_s( "Error reallocation aligned offset memory.");
return -1;
}
if ( ( (((int)ptr) + off_set) % alignment ) == 0)
printf_s( "This pointer, %d, is offset by %d on alignment of %d\n",
ptr, off_set, alignment);
else
printf_s( "This pointer, %d, does not satisfy offset %d and "
"alignment %d\n", ptr, off_set, alignment);
// Note that _aligned_free works for both _aligned_malloc
// and _aligned_offset_malloc. Using free is illegal.
_aligned_free(ptr);
}