《Cracking the Coding Interview》——第13章:C和C++——题目9
2014-04-25 20:47
447 查看
2014-04-25 20:37
题目:请设计一个字节对齐的malloc函数,配套上对应的free函数。要求这个函数分配出的内存块儿的首地址是某个值n的整数倍,n是2的整次幂,比如128、1024之类的。
解法:默认的malloc分配的首地址是不确定的,所以我们需要多分配一些内存,才能保证其中至少有一个字节能满足上述的要求,作为首地址。多余的地址不会被使用,但也要一起释放。每n个字节里,肯定有一个字节的地址是n的整数倍。所以我们至多需要多多分配n个字节。找到那个字节,作为结果返回即可。malloc说完了,free还存在一个问题。怎么知道最初由malloc分配的真实首地址呢?答案是:malloc的时候就找个地方存起来。至于存哪儿,放在那个内存块儿的前面或者后面都行,对于普通的far指针,需要额外四个字节的空间。这样要free的时候就不会抓瞎了。
代码:
题目:请设计一个字节对齐的malloc函数,配套上对应的free函数。要求这个函数分配出的内存块儿的首地址是某个值n的整数倍,n是2的整次幂,比如128、1024之类的。
解法:默认的malloc分配的首地址是不确定的,所以我们需要多分配一些内存,才能保证其中至少有一个字节能满足上述的要求,作为首地址。多余的地址不会被使用,但也要一起释放。每n个字节里,肯定有一个字节的地址是n的整数倍。所以我们至多需要多多分配n个字节。找到那个字节,作为结果返回即可。malloc说完了,free还存在一个问题。怎么知道最初由malloc分配的真实首地址呢?答案是:malloc的时候就找个地方存起来。至于存哪儿,放在那个内存块儿的前面或者后面都行,对于普通的far指针,需要额外四个字节的空间。这样要free的时候就不会抓瞎了。
代码:
// 13.9 Implement a memory-aligned malloc(), which returns a block of memory, and the address of the first byte is a multiple of a power of 2. #include <cstdio> #include <cstdlib> using namespace std; void *aligned_malloc(int nbytes, int align) { // boundary check if (nbytes < 1 || align < 1) { return nullptr; } // make sure that align is a power of 2 while ((align & align - 1) != 0) { align = (align & align - 1); } void *p1, *p2; p1 = (void *)malloc(nbytes + align - 1 + sizeof(void *)); if (p1 == nullptr) { return nullptr; } p2 = (void *)(((size_t)p1 + align - 1 + sizeof(void *)) & (~(align - 1))); ((void **)p2)[-1] = p1; return p2; } void aligned_free(void *ptr) { if (ptr == nullptr) { return; } free(((void **)ptr)[-1]); } int main() { void *p1 = aligned_malloc(100, 4096); void *p2 = malloc(100); printf("p1 = %p\n", p1); printf("p2 = %p\n", p2); aligned_free(p1); free(p2); return 0; }
相关文章推荐
- 《Cracking the Coding Interview》——第13章:C和C++——题目2
- 《Cracking the Coding Interview》——第13章:C和C++——题目3
- 《Cracking the Coding Interview》——第13章:C和C++——题目4
- 《Cracking the Coding Interview》——第13章:C和C++——题目5
- 《Cracking the Coding Interview》——第13章:C和C++——题目6
- 《Cracking the Coding Interview》——第13章:C和C++——题目7
- 《Cracking the Coding Interview》——第13章:C和C++——题目1
- 《Cracking the Coding Interview》——第13章:C和C++——题目8
- 《Cracking the Coding Interview》——第13章:C和C++——题目10
- 《Cracking the Coding Interview》——第2章:链表——题目3
- 《Cracking the Coding Interview》——第5章:位操作——题目1
- 《Cracking the Coding Interview》——第7章:数学和概率论——题目7
- 《Cracking the Coding Interview》——第8章:面向对象设计——题目3
- 《Cracking the Coding Interview》——第8章:面向对象设计——题目7
- 《Cracking the Coding Interview》——第14章:Java——题目2
- 《Cracking the Coding Interview》——第18章:难题——题目3
- 《Cracking the Coding Interview》——第2章:链表——题目4
- 《Cracking the Coding Interview》——第5章:位操作——题目2
- Cracking the Coding Interview 题目分析笔记—— Array and String
- 《Cracking the Coding Interview》——第9章:递归和动态规划——题目1