Aligned malloc in C++

本文详细解释了C++中实现对齐malloc的原理,通过分配额外的空间来确保内存对齐,并在释放时能够正确找到原始分配的指针。通过位运算确定对齐边界,并在返回的指针前存储原始分配的指针地址。
摘要由CSDN通过智能技术生成
void *aligned_malloc(size_t required_bytes, size_t alignment) {
  void *p1;
  void **p2;
  int offset=alignment-1+sizeof(void*);
  if((p1=(void*)malloc(required_bytes+offset))==NULL)
  return NULL;
  p2=(void**)(((size_t)(p1)+offset)&~(alignment-1));  //line 5
  p2[-1]=p1; //line 6
  return p2;
}

p1 is the actual allocation. p2 is the pointer being returned, which references memory past the point of allocation and leaves enough space for both allignment AND storing the actual allocated pointer in the first place. when aligned_free() is called, p1 will be retrieved to do the "real" free().

Regarding the bit math, that gets a little more cumbersome, but it works.

p2=(void**)(((size_t)(p1)+offset)&~(alignment-1));  //line 5

Remember, p1 is the actual allocation reference. For kicks, lets assume the following, with 32bit pointers:

alignment = 64 bytes
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值