摘自:http://www.blogjava.net/cjren/archive/2006/07/06/56989.aspx
印象中函数的第啊用是压栈实现的
Stack vs Heap Allocation
How the memory of the computer is organized for a running program? When a program is loaded into memory, it is organized into three areas of memory, called segments: the text segment, stack segment, and heap segment. The text segment (sometimes also called the code segment) is where the compiled code of the program itself resides. This is the machine language representation of the program steps to be carried out, including all functions making up the program, both user defined and system.
计算机的内存是如何为一个运行的程序组织的呢?当程序被加载到内存中时,它被组织成为3个区域:代码区,栈区,堆区。代码区就是存放你的程序的编译后的可执行代码的地方,它是程序被一步一步执行的机器语言的表述,包括所有用户定义和系统定义的组成程序的函数。
The remaining two areas of system memory is where storage may be allocated by the compiler for data storage. The stack is where memory is allocated for automatic variables within functions. A stack is a Last In First Out (LIFO) storage device where new storage is allocated and deallocated at only one ``end'', called the Top of the stack. This can be seen in Figure 14.13.
figure14.13.gif
另外两个系统内存被用做数据存储(数据区)。stack(栈)是被用作为函数开辟自动变量的内存区域。栈区是后进先出的存储机制,新开辟的内存在栈的顶端。
When a program begins executing in the function main(), space is allocated on the stack for all variables declared within main(), as seen in Figure 14.13(a). If main() calls a function, func1(), additional storage is allocated for the variables in func1() at the top of the stack as shown in Figure 14.13(b). Notice that the parameters passed by main() to func1() are also stored on the stack. If func1() were to call any additional functions, storage would be allocated at the new Top of stack as seen in the figure. When func1() returns, storage for its local variables is deallocated, and the Top of the stack returns to to position shown in Figure 14.13(c). If main() were to call another function, storage would be allocated for that function at the Top shown in the figure. As can be seen, the memory allocated in the stack area is used and reused during program execution. It should be clear that memory allocated in this area will contain garbage values left over from previous usage.
The heap segment provides more stable storage of data for a program; memory allocated in the heap remains in existence for the duration of a program. Therefore, global variables (storage class external), and static variables are allocated on the heap. The memory allocated in the heap area, if initialized to zero at program start, remains zero until the program makes use of it. Thus, the heap area need not contain garbage.
heap(堆)为程序提供更为可靠的存储区域。堆在程序存活期会一直存在。所以,全局变量,静态变量都是在堆中开辟的内存。在对中开辟的内存,如果在程序一开始初始化为0,它就会保持为0直到程序用到它为止。所以,堆中不需要包含垃圾数据。
小结:
Stack: automatic variables within functions栈----函数的自动变量(局部变量)
Heap: global variables (storage class external), and static variables堆----全局变量,静态变量