共用方式為


_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),這表示函式保證不會修改全域變數且傳回的指標不會產生別名。 如需詳細資訊,請參閱 noaliasrestrict

如果記憶體配置失敗或者要求大小大於 _HEAP_MAXREQ,這個函式會將 errno 設為 ENOMEM。 如需 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);
}
  

請參閱

參考

資料對齊