gpt4 book ai didi

c - malloc() 如何完成字节对齐?

转载 作者:太空宇宙 更新时间:2023-11-04 07:06:51 24 4
gpt4 key购买 nike

我目前正在阅读一个用于对齐内存分配和释放分配内存的程序。这是 C 代码:

/**
* Aligned memory allocation
* param[in] size Bytes to be allocated
* param[in] alignment Alignment bytes
* return Address of allocated memory
*/
inline void* _al_malloc(size_t size, size_t alignemt)
{
size_t a = alignment - 1;
size_t word_length = sizeof(void*);
void* raw = malloc(word_length + size + a);
if (!raw)
{
return 0;
}
void* ptr = (void*)((size_t(raw) + word_length + a) & ~a);
*((void**)ptr - 1) = raw;
return ptr;
}



/**
* Free allocated memory
*/
inline void _al_free(void * ptr)
{
if (!ptr)
{
return;
}
void* raw = *((void**)ptr - 1);
free(raw);
}

这些操作如何确保字节对齐内存?

最佳答案

它分配额外的内存,然后移动返回指针的起始地址,使其正确对齐(可能留下几个未使用的字节)。

更详细:

size_t a = alignment - 1;

如果 alignment 是 2 的幂,这将给出所需的额外字节数和对齐指针中不允许的地址位的掩码。

例如,如果对齐方式为 8,我们可能需要分配 7 个额外字节以确保其中一个字节以 8 对齐。

size_t word_length = sizeof(void*);

计算额外指针的大小(稍后 free 需要)。

void* raw = malloc(word_length + size + a);

分配所需的内存块 + 指针的大小 + 我们可能需要对齐的额外字节。

if (!raw)
{
return 0;
}

如果我们失败,返回一个空指针。

void* ptr = (void*)((size_t(raw) + word_length + a) & ~a);

现在得到一个新指针,它是原始指针+保存空间+正确对齐所需的字节数。

*((void**)ptr - 1) = raw;

同时保存来自 malloc 的原始指针,因为稍后需要释放它。

return ptr;

完成。

关于c - malloc() 如何完成字节对齐?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32307822/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com