这里主要是以 C 语言为例,其他语言开发的程序,每个进程都会有一个类似的空间。下面是一段 C 代码:
#include <stdlib.h> #include <stdio.h> double t[0x02000000]; void segments() { static int s = 42; void *p = malloc(2); printf("stack %010p brk %010p heap %010p " "static %010p static %010p text %010p ", &p, sbrk(0),p,t,&s,segments); } void writeFreeSpace() { char *p = sbrk(0) - 1; *p = 1; printf("assign to sbrk(0)-1 is succed! "); p = sbrk(0) + 1; *p = 1; printf("assign to sbrk(0)+1 is succed! "); } int main(int argc, char *argv[]) { segments(); writeFreeSpace(); exit(0); }
这里主要打印了:指针 p 的地址(stack),进程当前的 break 的位置( heap 的边界),指针 p 指向的地址(heap),全局变量 t 的地址,局部 static 变量的地址,还有函数 segments() 的地址。
使用 gcc 便以后,这段代码的运行结果如下:
stack 0xbfaa9edc brk 0x18856000 heap 0x18835008 static 0x0804a060 static 0x0804a024 text 0x08048494 Size of heap: 20ff8 assign to sbrk(0)-1 is succed! Segmentation fault
这很好的证明了下图中的分布关系:
其中,可能不常见的是 sbrk() 函数。一般情况下,应用编程的时候不推荐使用 sbrk(),所以我们见得少。通过 man 得知,sbrk( int ) 是用来增加 Heap 的大小的,当给它喂参数 0 ,它返回 Heap 的边界( sbrk(0) 返回的地址已经在 heap() 之外了,可以改动 writeFreeSpace() 中的地址尝试;从上面可以看出,这里 heap 的最小值默认是 132k Bytes(20ff8+8=21000),前面8 个 byte 是保留的,具体作用需要再作了解)。
valgrind
Valgrind是一套用于内存调试、内存泄漏检测以及性能分析的软件开发工具。下面是来自它官网的介绍:
The Valgrind tool suite provides a number of debugging and profiling tools that help you make your programs faster and more correct. The most popular of these tools is called Memcheck. It can detect many memory-related errors that are common in C and C++ programs and that can lead to crashes and unpredictable behaviour.
The Valgrind distribution currently includes six production-quality tools: a memory error detector, two thread error detectors, a cache and branch-prediction profiler, a call-graph generating cache and branch-prediction profiler, and a heap profiler. It also includes three experimental tools: a stack/global array overrun detector, a second heap profiler that examines how heap blocks are used, and a SimPoint basic block vector generator. It runs on the following platforms: X86/Linux, AMD64/Linux, ARM/Linux, ARM64/Linux, PPC32/Linux, PPC64/Linux, PPC64BE/Linux, S390X/Linux, MIPS32/Linux, MIPS64/Linux, ARM/Android (2.3.x and later), X86/Android (4.0 and later), MIPS32/Android, X86/Darwin and AMD64/Darwin (Mac OS X 10.9, with limited support for 10.8).
快速上手:http://valgrind.org/docs/manual/quick-start.html