关于堆与栈的,今天刚看的,并总结的...
栈(stack):是自动分配变量,以及函数调用所使用的一些空间(所谓的局部变量),地址由高向低减少;
堆(heap):由malloc,new等分配的空间的地址,地址由低向高增长。
自己所编写的代码:
#include <iostream>
using namespace std;
void main()
{
int a;
int b;
int *p1;
int *p2;
cout<<&a<<endl<<&b<<endl<<&p1<<endl<<&p2<<endl<<endl;
//结果显示:0012FF7C,0012FF78,0012FF74,0012FF70;可见,栈中的地址是减少的
int *p3=new int[1];
int *p4=new int[1];
cout<<p3<<endl<<p4<<endl;
//结果显示:003907A8,003907E0;可见,堆中地址是增加的
}
(2)stack
这个是个先进后出的数据结构,通过pushl和popl来实现。不仅可以储存变量,还可以储存函数地址,在多任务系统中实现任务切换。通常来说,1000个字节足够大了。因为通常不会通过函数传递太多的变量,这样的程序让自己也看不懂。有些OS把堆栈段放在程序段的后面,不分配一个独立的地址空间,因为实在没必要。比如FreeBSD. Windows 是按页分配的Stack段。
Every process has 4 segments, data, text, stack, and heap.
Data segment is for global, static data member, as well as static variable in a function. So, in your example, a, pl, and d are in data segment.
Text segment is for code, all the compile generated (corresponding to your source code) code stored in this are.
Stack is for local variables as well as the activation record of function call. So, c and p2 of your example are in this area. Activation recrod includes at least returning address, return value, and parameter. So, the parameter b of function f is in this area.
Heap is for dynamically allocated memory (many OS put the shared library here as well). In your example, you did not show any code that dynamically allocate memory for pl and p2. If you do, the memory pointer by pl and p2 will be in heap, for example:
pl = new int;
p2 = (int*)malloc(sizeof(int));
It is important to remember that pl and p2 themself are not in heap but the memory they point to might.