最近我一直在研究glibc malloc实现的内部机制。但是,有一个关于bin索引的问题我似乎无法理解。所以,在malloc_state结构体内,我们有以下声明,为了简洁起见进行了轻微格式化:
struct malloc_state
{
/*
.
.
Some declarations
.
.
*/
/* Set if the fastbin chunks contain recently inserted free blocks. */
/* Note this is a bool but not all targets support atomics on booleans. */
int have_fastchunks;
/* Fastbins */
mfastbinptr fastbinsY[NFASTBINS];
/* Base of the topmost chunk -- not otherwise kept in a bin */
mchunkptr top;
/* The remainder from the most recent split of a small request */
mchunkptr last_remainder;
/* Normal bins packed as described above */
mchunkptr bins[NBINS * 2 - 2];
/* Bitmap of bins */
unsigned int binmap[BINMAPSIZE];
/*
.
.
Some more declarations
.
.
*/
};
现在我的问题与此结构中bins数组的声明有关。bins数组声明如下:
mchunkptr bins[NBINS * 2 - 2];
根据我的理解,通过以下定义的bin_at宏来获取指向bins的指针:typedef struct malloc_chunk *mbinptr;
/* addressing -- note that bin_at(0) does not exist */
#define bin_at(m, i) \
(mbinptr) (((char *) &((m)->bins[((i) - 1) * 2])) \
- offsetof (struct malloc_chunk, fd))
现在具体来说,我的问题如下。为什么bin数组中保留的数量大约是两倍?我知道其中一个bin用于未排序的块(由free函数调用导致),并且有NBINS个bin用于已经按大小排序的空闲块。但是,我不理解剩余bin的用途。
我猜测这背后有一定的原因。然而,从源代码中看不出来这一点。如果你们有任何指示或者文档可以解释其原因,那将非常感激!
提前感谢您!