It is not necessary true. I have seen something like this and also seen something completely different. It is better to say that the memory layout of a process is depended on compiler/loader and/or OS.
全局变量和静态变量,无论在何处声明的静态变量,都在data中?Yes.
每调用一次函数,都要以这个函数的activation record 压栈,放些返回地址,返回值,参数,还有此函数中声明的局部变量。
heap用来放需动态申请内存的指针。
是不是这样??
Mostly right. Just to clarify one point, that is heap is for the dynamically allocated memory. This memory should be pointed by a pointer type variable. The pointer variable itself will not be on heap. So, "heap用来放需动态申请内存的指针" is not very clear because the pointer variable will not be on heap but the memory it points to could (but not have to).
如果
int f(int *p1)
{
static int *p2=new int;
}
这样,p1,p2放在哪里啊?
The memory p2 pointed to is on heap. "p2" itself is on data segment. "p1" itself is on stack, the memory it points to depending on the actual value passed in. For example:
int *ip1 = new int;
int j;
int *ip2 = &j;
f(ip1); //The memory pointed by the "p1" of f() is the same memory pointed by ip that is on heap. "p1" value is a copy of ip1. This also illustrated that pass pointer is pass by value.
f(&j); //The memory pointed by the "p1" of f() is j which is on stack.
f(ip2); //The memory pointed by the "p1" of f() is j which is on 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.
程序运行的时候,仅指函数(也不讨论98系与NT系对于内存管理的差别)。
如果函数中出现“ int a = 8;”这种语句,这是需要在栈中分配一个int大小的内存出来。如果用到了GlobalAlloc就是要向全局申请内存(范围指:在98中全局就是全计算机内存,在NT中就是本进程空间所占领的内存空间)。用后要释放,用GlobalFree。
一个进程可用内存空间为4G,可分在存放静态数据,代码,系统内存,堆,栈等。.活动记录一般存放调用参数、返回地址等内容。堆和栈最大的区别在于堆是由低地址向高地址分配内存,而栈是由高向低。全局和静态数据存放在全局数据区,其余的在栈中,用malloc 或 new 分配的内存位于堆中。一般来说栈在低地址,堆位于高地址。