用C不结盟++的malloc [英] Aligned malloc in C++

查看:118
本文介绍了用C不结盟++的malloc的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对书中问题13.9问题,破解编码访谈。
现在的问题是编写支持内存分配对齐alloc和free函数,并在答案code为如下:

I have a question on problem 13.9 in the book, "cracking the coding interview". The question is to write an aligned alloc and free function that supports allocating memory, and in the answer the code is given below:

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;
}

我对5号线和6行很困惑为什么你必须做一个和因为你已经加偏移到P1?又是什么[-1]是什么意思?感谢您提前帮助。

I am so confused with the line 5 and line 6. Why do you have to do an "and" since you have already add offset to p1? and what does [-1] mean? Thanks for the help in advance.

推荐答案

P1是实际分配。 P2是返回的指针,它引用的内存分配过去的点和叶足够的空间为排成一条直线和存储在首位的实际分配的指针。当aligned_free()被调用时,P1将检索到做真正的自由()。

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

记住,P1是实际分配的参考。对于踢,让我们假设下,用32位指针:

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

alignment = 64 bytes, 0x40
offset = 0x40-1+4 = 0x43
p1 = 0x20000110, a value returned from the stock malloc()

什么是重要的是原始的的malloc()的分配超出原始请求额外×43个字节的空间。这是为了确保双方对准数学的的为32位指针的空间可占:

What is important is the original malloc() that allocates an additional 0x43 bytes of space above and beyond the original request. This is to ensure both the alignment math and the space for the 32bit pointer can be accounted for:

p2=(void**)(((size_t)(p1)+offset)&~(alignment-1));  //line 5
p2 = (0x20000110 + 0x43) &~ (0x0000003F)
p2 = 0x20000153 &~ 0x0000003F
p2 = 0x20000153 & 0xFFFFFFC0
p2 = 0x20000140

P2被一个0X40边界上对齐(即,在0x3F的所有位都为0),并有足够的空间被留下来存储原始分配的4个字节的指针,用p1引用

p2 is aligned on a 0x40 boundary (i.e. all bits in 0x3F are 0) and enough space is left behind to store the 4-byte pointer for the original allocation, referenced by p1.

它一直的永久的,因为我做了比对数学,所以如果我f'ed了位的的有人纠正这一点。

It has been forever since i did alignment math, so if i f'ed up the bits, please someone correct this.

这篇关于用C不结盟++的malloc的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆