问题描述
c代码:
// program break mechanism
// TLPI exercise 7-1
#include <stdio.h>
#include <stdlib.h>
void program_break_test() {
printf("%10p\n", sbrk(0));
char *bl = malloc(1024 * 1024);
printf("%x\n", sbrk(0));
free(bl);
printf("%x\n", sbrk(0));
}
int main(int argc, char **argv) {
program_break_test();
return 0;
}
在编译以下代码时:
printf("%10p\n", sbrk(0));
我得到警告提示:
format ‘%p’ expects argument of type ‘void *’, but argument 2 has type ‘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()
;
- If requested memory is less than it,
brk()
will be used; - If requested memory is larger than or equals to it,
mmap()
will be used;
参数的默认值是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\n", sbrk(0));
char *bl = malloc(1024 * 1024);
printf("%10p\n", sbrk(0));
printf("malloc'd at: %10p\n", bl);
free(bl);
printf("%10p\n", 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()吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!