【发布时间】:2020-12-15 10:01:13
【问题描述】:
最近我一直在研究 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 的指针是使用定义如下的 bin_at 宏获得的:
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))
现在具体来说,我的问题如下。为什么 bins 数组中保留的 bin 数量大约是两倍?我知道有一个 bin 是为调用 free 产生的未排序的块保留的,并且有 NBINS 数量的 bin 用于已经大小排序的空闲块。但是,我不明白剩余垃圾箱的用途。
我怀疑这背后是有原因的。但是,从源代码来看,这对我来说并不清楚。如果你们中的任何人有一些关于为什么这样做的指示或文档,那将不胜感激!
提前谢谢你!
【问题讨论】: