chenglong7997

C 边界对齐的malloc和free函数实现

MSVC 下面有:

1 
2 void * _aligned_malloc(
3     size_t size, 
4     size_t alignment
5 );
Unix/Linux下面有:
1 int posix_memalign(void **memptr, size_t alignment, size_t size);

自己实现:
 1 #include <iostream>
 2 #include <stdlib.h>
 3 using namespace std;
 4 
 5 //by snape 2012-3-25
 6 
 7 void *aligned_malloc(size_t required_bytes, size_t alignment)
 8 {
 9     void *p1;    //orignal block
10     void **p2;    //aligned block
11 
12     int offset=alignment-1+sizeof(void*);
13     if( (p1=(void*)malloc(required_bytes+offset))==NULL )
14         return NULL;
15     //cast void* to void** to let p1 store into heap in the form of pointer
16     p2=(void**)( ((size_t)(p1)+offset) & ~(alignment-1) );    //add offset to p1 and then back to the aligned address
17     p2[-1]=p1;
18     return p2;
19 }
20 
21 void aigned_free(void *p2)
22 {
23     void* p1=((void**)p2)[-1];    //get the p1
24     free(p1);
25 }
26 
27 
28 
29 int main()
30 {
31     int size=10, align=16;
32     int *p=(int *)aligned_malloc(size, align);
33     
34     cout<<"The start address="<<p<<endl;
35     
36     aigned_free(p);
37 }

上面实现很考验对指针的掌握。原理不是很难。

Line12:分配内存的时候,加上alignment-1个空间,就能保证能够找到和alignment对齐的开始地址。多出来的sizeof(void*)是为了保存malloc最初返回的指针p1而分配的一个空间

Line 17: 保存原始的malloc返回的地址p1到对齐地址的前一个空间

posted on 2012-03-27 01:19 Snape 阅读(1849) 评论(0)  编辑 收藏 引用 所属分类: CTCI_C++


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


导航

<2012年3月>
26272829123
45678910
11121314151617
18192021222324
25262728293031
1234567

统计

常用链接

留言簿

随笔分类

随笔档案

文章分类

文章档案

my

搜索

最新评论

阅读排行榜

评论排行榜