题目:《程序员面试金典(第5版)》P281
编写支持对其分配的malloc和free函数,分配内存时,malloc函数返回的地址必须能被2的n次方整除。
//required_bytes为需要新建的字节数,alignment为首位置需要整除的数值
//按照题目要求,alignment应该是2的n次方
void* aligned_malloc(size_t required_bytes, size_t alignment)
{
size_t offset = alignment - 1 + sizeof(void*);
void* p = (void*)malloc(required_bytes+offset);
if (p == nullptr)
return nullptr;
void* res = (void*)(((size_t)(p)+offset)&~(alignment-1));//关键
void** tmp = (void**)res;
tmp[-1] = p;
return res;
}
void aligned_free(void* r)
{
if (r != nullptr)
{
void** tmp = (void**)r;
free(tmp[-1]);
r = nullptr;
}
}