您的位置:首页 > 其它

内存分配中的对齐操作

2013-05-27 05:32 183 查看
Problem

Memory operation with alignment

Solution

#include <iostream>


using namespace std;


int aligned_malloc(void **memptr, size_t alignment, size_t size)


{


    size_t len = size + alignment + sizeof(void *);


    void *ptr = malloc(len);


    if(ptr == NULL){


        return 0;


    }


    *memptr = (unsigned int *)((((unsigned)ptr) + alignment + sizeof(void *)) & ~(alignment - 1));


    *((unsigned int *)(((unsigned int *)*memptr) - 1)) = (unsigned)ptr;


    


    return 1;


}


int aligned_free(void *memptr)


{


    if(memptr == NULL){


        return 0;


    }


    else{


        free((void *)(*((unsigned int *)memptr - 1)));


        return 1;


    }


}


int main(int argc, char* argv[])


{


    for(int i = 1; i < 257; i *= 2){


        void *memptr = NULL;


        aligned_malloc(&memptr, i, 1000);


        cout << "aligned :" << i << " -- " << hex << (unsigned)memptr << endl;


        aligned_free(memptr);


    }


return 0;


}


Output

aligned :1 -- 396445


aligned :2 -- 396446


aligned :4 -- 396448


aligned :8 -- 396448


aligned :10 -- 396b20


aligned :20 -- 396b20


aligned :40 -- 396b40


aligned :80 -- 396b80


aligned :100 -- 396c00
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  内存分配 对齐 释放