_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);这意味着函数保证不修改全局变量,和返回的指针不用做别名。 有关更多信息,请参见 没有别名 和 限制。
如果内存分配失败或是如果请求的大小比_HEAP_MAXREQ 更大,则函数将 ENOMEM 设置为 errno 。 有关 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);
}