我正在阅读一些模型malloc(allocateMemory)的代码.我已经发布了一部分代码,但我无法理解size =(size_in_bytes + sizeof(int) - 1)/ sizeof(int); (已发布代码中的最后一行)
void initializeHeap(void) {
/* each chunk requires two signatures, one at the top and one
* at the bottom, so the available space inside a chunk is
* the number of elements in the chunk minus 2
*/
unsigned available_size = HEAP_SIZE - 2;
if (initialized) { return; }
/* write signatures at top and bottom of chunk */
memory_pool[0] = available_size;
memory_pool[HEAP_SIZE - 1] = available_size;
initialized = true;
}
void* allocateMemory(unsigned size_in_bytes) {
int size;
unsigned chunk;
int chunk_size;
initializeHeap();
size = (size_in_bytes + sizeof(int) - 1) / sizeof(int);
Run Code Online (Sandbox Code Playgroud)
它的大小可以达到倍数sizeof(int).这通常用于对齐目的,因为在某些机器(例如SPARC)上,您无法访问在奇数地址上对齐的32位宽值(典型症状是SIGBUS).即使在支持非对齐访问的处理器上,例如x86和PPC,它通常比对齐访问慢.它有助于防止缓存分裂,其中一半数据位于一个缓存行中,一半位于另一个缓存行中 - 这会减慢对值的访问速度2倍,这非常令人讨厌.
Malloc必须假设最大可能的有用对齐,因为它不知道它分配的东西的大小.通常是4,8或16个字节,具体取决于机器.
| 归档时间: |
|
| 查看次数: |
444 次 |
| 最近记录: |