如何使用malloc()完成字节对齐?
我目前正在阅读用于对齐内存分配和空闲分配内存的程序。 这是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的幂,则这将给出所需的额外字节数和对齐指针中不允许的地址位掩码。
例如,如果alignment是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
的原始指针,因为以后需要free
它。
return ptr;
完成。