如何申请对齐的动态内存?

来源:互联网 发布:江西网络干部学院app, 编辑:程序博客网 时间:2024/04/28 02:45

   

    windows下有现成的函数:_align_malloc, _align_realloc, _align_free,_align_offset_malloc,_aligned_offset_realloc

    见

    http://msdn.microsoft.com/zh-tw/data/8z34s9c6 

    以及

     http://msdn.microsoft.com/zh-tw/data/fs9stz4e

    下面是一个测试:

    http://wenku.baidu.com/view/223fb6737fd5360cba1adba5.html

// 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);} // Copy Code This pointer, 3280880, is aligned on 16This pointer, 3280880, is aligned on 16This pointer, 3280891, is offset by 5 on alignment of 16This pointer, 3280891, is offset by 5 on alignment of 16

   

原创粉丝点击