glibc下malloc的理解

本文介绍了glibc下的malloc,包括其在多线程环境下的工作原理,如chunk、bin和特殊chunk的概念。malloc在多线程中可能会引发竞争,而ptmalloc解决了这一问题,提供线程局部的heap。文章还探讨了malloc如何选择系统调用,并详细解释了arena、heap和chunk的数据结构,以及bin管理chunk的方式。
摘要由CSDN通过智能技术生成

0.1 简介

在linux中常见的malloc是glibc的malloc,经对glibc上malloc修改有适用于linux多线程的mallocdlmalloc,还有一个ptmalloc2这两者有区别,其区别在于:

dlmalloc 在子线程和父线程同时调用malloc时会有竞争,且只会有一个能够从heap中分配到空间。并且freelist data structure 是被众进程共享的。

ptmalloc2 可以确保不有这种竞争,而且freelist 是各自进程独享自己的一个结构体。ptmalloc是per thread malloc之意。


1.malloc用例

/* Per thread arena example. */
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/types.h>

void* threadFunc(void* arg) {
        printf("Before malloc in thread 1\n");
        getchar();
        char* addr = (char*) malloc(1000);
        printf("After malloc and before free in thread 1\n");
        getchar();
        free(addr);
        printf("After free in thread 1\n");
        getchar();
}

int main() {
        pthread_t t1;
        void* s;
        int ret;
        char* addr;

        printf("Welcome to per thread arena example::%d\n",getpid());
        printf("Before malloc in main thread\n");
        getchar();
        addr = (char*) malloc(1000);
        printf("After malloc and before free in main thread\n");
        getchar();
        free(addr);
        printf("After free in main thread\n");
        getchar();
        ret = pthread_create(&t1, NULL, threadFunc, NULL);
        if(ret)
        {
                printf("Thread creation error\n");
                return -1;
        }
        ret = pthread_join(t1, &s);
        if(ret)
        {
                printf("Thread join error\n");
                return -1;
        }
        return 0;
}
情景1

main threadmalloc之前

sploitfun@sploitfun-VirtualBox:~/ptmalloc.ppt/mthread$ ./mthread 
Welcome to per thread arena example::6501
Before malloc in main thread
...
sploitfun@sploitfun-VirtualBox:~/ptmalloc.ppt/mthread$ cat /proc/6501/maps
08048000-08049000 r-xp 00000000 08:01 539625   /home/sploitfun/ptmalloc.ppt/mthread/mthread
08049000-0804a000 r--p 00000000 08:01 539625   /home/sploitfun/ptmalloc.ppt/mthread/mthread
0804a000-0804b000 rw-p 00001000 08:01 539625   /home/sploitfun/ptmalloc.ppt/mthread/mthread
b7e05000-b7e07000 rw-p 00000000 00:00 0 

再未用malloc时,尚未分配heap

情景2
sploitfun@sploitfun-VirtualBox:~/ptmalloc.ppt/mthread
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值