了解 glibc malloc 分级实现

Hea*_*lar 7 c malloc glibc bins

最近我一直在研究 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
       .
       .
  */
};
Run Code Online (Sandbox Code Playgroud)

现在我的问题是关于此结构中 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))
Run Code Online (Sandbox Code Playgroud)

现在具体来说,我的问题如下。为什么 bins 数组中保留的 bin 数量大约是两倍?据我了解,有一个 bin 是为调用 free 所产生的未排序块保留的,并且有 NBINS 数量的 bin 是用于已经大小排序的空闲块。但是,我不明白剩余垃圾箱的用途。

我怀疑这背后是有原因的。然而,从源代码来看,我并不清楚这一点。如果你们中的任何人有一些关于为什么这样做的指示或文档,我们将不胜感激!

先感谢您!

ric*_*ici 6

由于 bins 是双向链表,因此每个 bin 头包含两个指针,而不是一个:第一个指针指向列表的头部,第二个指针指向列表的尾部。这就是为什么指针的数量是容器数量的两倍。(请注意,未使用 bin 编号 0,因此 bin 的数量实际上是NBINS - 1。)

正如双向链表实现中常见的那样,该列表实际上是循环的;标题可以被视为链接条目。这避免了在添加元素之前检查 bin 是否存在的必要。(在空 bin 中,first 和 last 都指向 bin 标头本身。)但是,a 中的前向 ( fd) 和后向 ( ) 指针并不位于块的开头。为了将 bin 数组中的这对指针视为一个 chunk 条目,需要将这对指针的地址反向偏移.bkmalloc_chunkfdmalloc_chunk

图表可能会有所帮助。这是垃圾箱中有两个块时的样子:

     Bins Array                Chunk 0                Chunk 1 

+--> XXXXXXXXXX <-\     /--> +--------+ <-\     /--> +--------+ <-----+
|    XXXXXXXXXX    \   /     |  p_sz  |    \   /     |  p_sz  |       |
|    XXXXXXXXXX     \ /      +--------+     \ /      +--------+       |
|    XXXXXXXXXX      X       |   sz   |      X       |   sz   |       |
|    +--------+     / \      +--------+     / \      +--------+       |
|    | [2i-2] | -->/   \     |   fd   | -->/   \     |   fd   | ->+   |
|    +--------+         \    +--------+         \    +--------+   |   |
|    | [2i-1] | -->+     \<- |   bk   |          \<- |   bk   |   |   |
|    +--------+    |         +--------+              +--------+   |   |
|                  |                                              |   |
|                  +----------------------------------------------+---+
|                                                                 |
+<----------------------------------------------------------------+
Run Code Online (Sandbox Code Playgroud)

sXXX显示反向偏移量,使指针保持一致。