我正在阅读一个模型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);发布于 2009-11-05 03:09:46
它将大小向上舍入为sizeof(int)的倍数。这通常是为了对齐目的,因为在某些机器上(例如SPARC),您无法访问在奇数地址上对齐的32位宽值(典型症状是SIGBUS)。即使在支持非对齐访问的处理器上,比如x86和PPC,它也常常比对齐访问慢。它还有助于防止高速缓存分裂,其中一半的数据在一个高速缓存线中,另一半在另一个高速缓存线中-这会使对该值的访问速度减慢2倍,这是非常糟糕的。
Malloc必须假设最大可能的有用对齐,因为它不知道它正在分配的东西的大小。通常是4、8或16字节,具体取决于机器。
发布于 2009-11-05 03:08:10
它将大小四舍五入为sizeof(int)的倍数。size将是大于或等于size_in_bytes所需空间的最小数量的int。
https://stackoverflow.com/questions/1675931
复制相似问题