I. prerequisites-program memory allocation
The memory occupied by a C/C ++ compiled program is divided into the following parts:
1. STACK: the stack zone is automatically allocated and released by the compiler, and stores function parameter values and local variable values. The operation method is similar to the stack in the data structure.
2. Heap-generally assigned and released by the programmer. If the programmer does not release the heap, it may be recycled by the OS at the end of the program. Note that it is different from the heap in the data structure. The allocation method is similar to the linked list.
3. Global (static)-the storage of global variables and static variables is put together, and the initialized global variables and static variables are in one area, uninitialized global variables and uninitialized static variables are in another adjacent area. -The system is released after the program ends.
4. Text Constant Area-constant strings are placed here. The program is released by the System
5. program code area-stores the binary code of the function body.
Ii. Example Program
This is written by a senior. It is very detailed.
// Main. cpp
Int A = 0; global initialization Zone
Char * P1; uninitialized globally
Main ()
{
Int B; // Stack
Char s [] = "ABC"; // Stack
Char * P2; // Stack
Char * P3 = "123456"; 123456 \ 0 "; // in the constant area, P3 on the stack.
Static int C = 0; // global (static) initialization Zone
P1 = (char *) malloc (10 );
P2 = (char *) malloc (20 );
// The allocated 10-byte and 20-byte areas are in the heap area.
Strcpy (P1, "123456"); // 123456 \ 0 is placed in the constant area, and the compiler may optimize it into a place with the "123456" pointed to by P3.
}
FW: Division of programs in memory ()