_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);
}