`
mqzhuang
  • 浏览: 185428 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
文章分类
社区版块
存档分类
最新评论

Glibc内存管理--ptmalloc2源代码分析(二十六)

阅读更多

5.7.2.2 分配small bin chunk

 

如果所需的 chunk 大小属于 small bin ,则会执行如下的代码:

/*
    If a small request, check regular bin.  Since these "smallbins"
    hold one size each, no searching within bins is necessary.
    (For a large request, we need to wait until unsorted chunks are
    processed to find best fit. But for small ones, fits are exact
    anyway, so we can check now, which is faster.)
  */
  if (in_smallbin_range(nb)) {
    idx = smallbin_index(nb);
    bin = bin_at(av,idx);

    if ( (victim = last(bin)) != bin) {
      if (victim == 0) /* initialization check */
        malloc_consolidate(av);
      else {
        bck = victim->bk;
        if (__builtin_expect (bck->fd != victim, 0))
          {
            errstr = "malloc(): smallbin double linked list corrupted";
            goto errout;
          }
        set_inuse_bit_at_offset(victim, nb);
        bin->bk = bck;
        bck->fd = bin;

        if (av != &main_arena)
          victim->size |= NON_MAIN_ARENA;
        check_malloced_chunk(av, victim, nb);
        void *p = chunk2mem(victim);
        if (__builtin_expect (perturb_byte, 0))
          alloc_perturb (p, bytes);
        return p;
      }
    }
  }

 如果分配的 chunk 属于 small bin ,首先查找 chunk 所对应 small bins 数组的 index ,然后根据 index 获得某个 small bin 的空闲 chunk 双向循环链表表头,然后将最后一个 chunk 赋值给 victim ,如果 victim 与表头相同,表示该链表为空,不能从 small bin 的空闲 chunk 链表中分配,这里不处理,等后面的步骤来处理。如果 victim 与表头不同,有两种情况,如果 victim 0 ,表示 small bin 还没有初始化为双向循环链表,调用 malloc_consolidate() 函数将 fast bins 中的 chunk 合并。否则,将 victim small bin 的双向循环链表中取出,设置 victim chunk inuse 标志,该标志处于 victim chunk 的下一个相邻 chunk size 字段的第一个 bit 。从 small bin 中取出一个 chunk 也可以用 unlink() 宏函数,只是这里没有使用。

接着判断当前分配区是否为非主分配区,如果是,将 victim chunk size 字段中的表示非主分配区的标志 bit 清零,最后调用 chunk2mem() 函数获得 chunk 的实际可用的内存指针,将该内存指针返回给应用层。到此从 small bins 中分配 chunk 的工作完成了,但我们看到,当对应的 small bin 中没有空闲 chunk ,或是对应的 small bin 还没有初始化完成,并没有获取到 chunk ,这两种情况都需要后面的步骤来处理。

 

 

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics