C language C memory model

Reference:
C language memory model (memory organization)
C language program memory layout (memory model)

image.png

  • The program code area (code area)
    stores the binary code of the function body.

  • Global data area (data area) The
    global data area is divided into three areas.
    Initialized global variables and static variables are in one area;
    uninitialized global variables and uninitialized static variables are in another adjacent area;
    constant data is stored in another area.
    These data are released by the system after the program ends. What we call the BSS segment (bss segment) usually refers to a memory area used to store uninitialized global variables in the program. BSS is the abbreviation of English Block Started by Symbol.
    The default value of uninitialized global variables is 0, and the value of uninitialized local variables is garbage (arbitrary value).

  • The stack area
    is automatically allocated and released by the compiler, storing function parameter values, local variable values, etc. Its operation is similar to the stack in the data structure.

  • The heap area is
    generally allocated and released by the programmer. If the programmer does not release it, the OS may reclaim it when the program ends. malloc, calloc, freeAnd other operational functions is this memory.
    Note that it is different from the heap in the data structure, and the allocation method is similar to a linked list.

  • Command line parameter area
    Stores the values ​​of command line parameters and environment variables.

Example

int a = 0;  // 全局初始化区(④区)
char *p1;  // 全局未初始化区(③区)
int main()
{
    
    
    int b;  // 栈区
    char s[] = "abc";  // 栈区
    char *p2;  // 栈区
    char *p3 = "123456"; // 123456\0 在常量区(②),p3在栈上,体会与 char s[]="abc"; 的不同
    static int c = 0;  // 全局初始化区
    p1 = (char *)malloc(10),  // 堆区
    p2 = (char *)malloc(20);  // 堆区
    // 123456\0 放在常量区,但编译器可能会将它与p3所指向的"123456"优化成一个地方
    strcpy(p1, "123456");
}

Guess you like

Origin blog.csdn.net/u014099894/article/details/111472760