malloc分配内存的实现中brk和mmap的区别

malloc函数族:

       #include <stdlib.h>

       void *malloc(size_t size);
       void free(void *ptr);
       void *calloc(size_t nmemb, size_t size);
       void *realloc(void *ptr, size_t size);
       void *reallocarray(void *ptr, size_t nmemb, size_t size);

malloc:
分配size大小的内存空间,并返回一个指向这片空间的指针ptr。这片空间并为被初始化。若size=0,则返回NULL,或者一个之后能够被正确free的指针。
Linux采用积极的内存分配策略,这意味着即使返回了一个非空指针,并不一定能够保证内存中有足够的空间。。若不够,则OOM killer会杀掉若干个进程腾出空间。
在分配空间大小小于MMAP_THRESHOLD的时候,malloc使用brk()函数分配空间,若大于,则使用mmap函数作为真正的实现函数。MMAP_THRESHOLD默认大小是128kb,可以使用 mallopt函数修改。

mmap函数

       #include <sys/mman.h>
       void *mmap(void *addr, size_t length, int prot, int flags, int fd, off_t offset);
       int munmap(void *addr, size_t length);

mmap在调用他的程序的虚拟内存上创建一个新的映射,addr指向映射地址的起始地址,若为NULL,则内核自己选择。映射长度为length,proc参数决定这片地址的保护,如可读,可写,可执行,不可接触。 flag参数决定这片地址对其他进程是否可见。

brk函数

       #include <unistd.h>
       int brk(void *addr);
       void *sbrk(intptr_t increment);

brk()函数族改变调用程序的虚拟内存中数据段的结束位置(program break)增加这个位置来增加数据区大小以达到分配空间的目的。
glibc的brk是brk系统调用的一个包装,返回值略有不同,实作是一样的。

画图比较

在下图中,brk从已初始化数据区的最后面,由于bss区已经并入数据区,从bss的末尾向堆以移动指针的方式开辟空间;mmap在对区域中分配空间
在这里插入图片描述

参考资料

linux中man手册

malloc

MALLOC(3)                  Linux Programmer's Manual                 MALLOC(3)

NAME
       malloc, free, calloc, realloc - allocate and free dynamic memory

SYNOPSIS
       #include <stdlib.h>

       void *malloc(size_t size);
       void free(void *ptr);
       void *calloc(size_t nmemb, size_t size);
       void *realloc(void *ptr, size_t size);
       void *reallocarray(void *ptr, size_t nmemb, size_t size);

   Feature Test Macro Requirements for glibc (see feature_test_macros(7)):

       reallocarray():
           _GNU_SOURCE

DESCRIPTION
       The malloc() function allocates size bytes and returns a pointer to the
       allocated memory.  The memory is not initialized.  If size is  0,  then
       malloc()  returns either NULL, or a unique pointer value that can later
       be successfully passed to free().

       The free() function frees the memory space pointed  to  by  ptr,  which
       must  have  been  returned by a previous call to malloc(), calloc(), or
       realloc().  Otherwise, or if free(ptr) has already been called  before,
       undefined behavior occurs.  If ptr is NULL, no operation is performed.

       The  calloc()  function allocates memory for an array of nmemb elements
       of size bytes each and returns a pointer to the allocated memory.   The
       memory  is  set  to zero.  If nmemb or size is 0
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值