The area of memory occupied by a program compiled by C + + is generally divided into the following 5 parts: (1) Stack: The compiler automatically allocates and releases the parameters, local variables, etc. that are used to store functions. It operates in a manner similar to a stack in a data structure. (2) Heap: typically assigned and released by programmers (via Malloc/free, New/delete), if the programmer is not released, the program is reclaimed by the operating system at the end. It is different from the heap in the data structure and is distributed in a similar way to a linked list. (3) Global/static zones: The storage of global variables and static variables is placed in a block, initialized global variables and initialized static variables in an area, uninitialized global variables and uninitialized static variables in another adjacent area, after the end of the program is recycled by the operating system. (4) Literal constant area: store constant value, normal string, etc., do not allow modification, after the end of the program by the operating system recovery. (5) Program code area: the binary code that holds the function body.
Example:
#include <stdlib.h>
#include <string.h>
int a = 0; Global initialization Zone
char* P1; Global uninitialized Zone
int main () {
int A; Stack area
Char s[] = "ABC"; Stack area
char* P2; Stack area
char* p3 = "123456"; 123456\0 in the constant area, p3 in the stack area
static int c = 0; Global/Static initialization zone
P1 = (char*) malloc (10);
P2 = (char*) malloc (20); 10 and 20 bytes allocated in the heap area
strcpy (P1, "123456"); 123456\0 is placed in a constant area, the compiler might optimize it to a place with the "123456" that P3 points to
return 0;
}
C + +: Five memory allocation areas