C Advanced Memory Management (1)

The C language program we write has data and code to operate on the data, and the data is divided into global variables, local variables, static variables and so on. How do C programs distinguish and manage them when they are running? This is the memory management of the C language.

 

The essence of memory management in C language is to divide the memory into different areas, and a certain memory area will only store the corresponding data. The C language divides the memory space as follows:

 

 

1) Code segment: This area is mainly used to store the binary code of the compiled function body, string constants. This area is read-only. If you try to rewrite this area, the operating system will report the following error:

segmentation fault(core dumped)

2) data segment: This area mainly stores initialized global variables, static variables, and general constants.

3) BSS segment: This area mainly stores uninitialized global variables and static variables.

4) Heap area: manually applied for, manually released and recycled by the programmer. If the programmer does not release it manually, it will be reclaimed by the operating system after the program ends. The corresponding functions are malloc(), calloc(), free(), etc.

5) Stack area: It is automatically allocated, automatically released and recycled by the system, and stores the parameter values ​​of functions, local variables, etc.

 

Among them, the memory of the heap area and the stack area is allocated by the system when the program is executed. When the program needs to allocate memory, it will allocate memory, and it will not allocate when it is not needed (or reclaim it directly after allocation). The BSS area, data area, and code area are allocated memory by the compiler at the beginning of program execution. The memory of these three areas will always exist when the program is running, and will not be temporarily reclaimed.

 

Example:

#include<stdio.h>

#include<stdlib.h>

 

int a = 0;//data段

char *p1;// BSS segment

 

intmain()

{

       int b; //stack area

       char s[] = "123456";//"123456" is in the stack area

       char *p2;//stack area

       char *p3 = "abcde";//"abcde" in the code segment

       static int c = 0;//data段

       p1 = (char*)malloc(10);//heap area

 

      *p3 = 'A';//"abcde" is in the code segment, so it cannot be rewritten. After rewriting, a segmentation fault (core dumped) occurs.

 

       return 0;

}

 


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325428535&siteId=291194637