malloc() 使用 brk() 还是 mmap()? [英] Does malloc() use brk() or mmap()?

查看:21
本文介绍了malloc() 使用 brk() 还是 mmap()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

c 代码:

// program break mechanism
// TLPI exercise 7-1

#include <stdio.h>
#include <stdlib.h>

void program_break_test() {
    printf("%10p
", sbrk(0));

    char *bl = malloc(1024 * 1024);
    printf("%x
", sbrk(0));

    free(bl);
    printf("%x
", sbrk(0));

}

int main(int argc, char **argv) {
    program_break_test();
    return 0;
}

编译以下代码时:

 printf("%10p
", sbrk(0));

我收到警告提示:

格式‘%p’需要‘void *’类型的参数,但参数2的类型为‘int’

问题 1:这是为什么?

在我malloc(1024 * 1024)之后,程序中断似乎没有改变.

And after I malloc(1024 * 1024), it seems the program break didn't change.

这是输出:

9b12000
9b12000
9b12000

问题 2: 进程是否在启动时在堆上分配内存以备将来使用?或者编译器改变了分配的时间点?否则,为什么?

Question 2: Does the process allocate memory on heap when start for future use? Or the compiler change the time point to allocate? Otherwise, why?

[更新] 总结:brk() 或 mmap()

在查看 TLPI 并检查手册页后(在 TLPI 作者的帮助下),现在我了解 malloc() 如何决定使用 brk()mmap(),如下:

After reviewing TLPI and check man page (with help from author of TLPI), now I understand how malloc() decide to use brk() or mmap(), as following:

mallopt() 可以设置参数来控制malloc()的行为,一般有一个名为M_MMAP_THRESHOLD的参数:

mallopt() could set parameters to control behavior of malloc(), and there is a parameter named M_MMAP_THRESHOLD, in general:

  • 如果请求的内存小于它,将使用brk()
  • 如果请求的内存大于或等于它,将使用mmap()

参数的默认值是128kb(在我的系统上),但是在我的测试程序中我使用了1Mb,所以选择了mmap(),当我改变时请求的内存为 32kb,我看到将使用 brk().

The default value of the parameter is 128kb (on my system), but in my testing program I used 1Mb, so mmap() was chosen, when I changed requested memory to 32kb, I saw brk() would be used.

这本书在 TLPI 第 147 页和第 1035 页中提到了这一点,但我没有仔细阅读那部分.

The book mentioned that in TLPI page 147 and 1035, but I didn't read carefully of that part.

参数的详细信息可以在mallopt()的手册页中找到.

Detailed info of the parameter could be found in man page for mallopt().

推荐答案

如果我们更改程序以查看 malloc 的内存在哪里:

If we change the program to see where the malloc'd memory is:

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

void program_break_test() {
  printf("%10p
", sbrk(0));

  char *bl = malloc(1024 * 1024);
  printf("%10p
", sbrk(0));
  printf("malloc'd at: %10p
", bl);

  free(bl);
  printf("%10p
", sbrk(0));

}

int main(int argc, char **argv) {
  program_break_test();
  return 0;
}

sbrk 不会改变可能更清楚一些.malloc 给我们的内存被映射到一个完全不同的位置.

It's perhaps a bit clearer that sbrk wouldn't change. The memory given to us by malloc is being mapped into a wildly different location.

您也可以在 Linux 上使用 strace 来查看进行了哪些系统调用,并发现 malloc 正在使用 mmap 来执行分配.

You could also use strace on Linux to see what system calls are made, and find out that malloc is using mmap to perform the allocation.

这篇关于malloc() 使用 brk() 还是 mmap()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆