C language memory management and Memory Management
The C language defines four memory areas:
1. Code area: it stores the program code and is read-only.
2. Global variables and static variables (static storage area) are allocated when the program is compiled, all variables (such as global variables, static variables, and string constants) exist during the entire running of the program. The variables allocated in this region are released at the end of the program, it has a long life cycle and is mainly used to transmit information between functions.
3. Create a function on the stack. When a function is executed, the storage units of local variables in the function can be created in the stack. The function is automatically released after execution ends. Stack memory allocation computation is built into the processor's Instruction Set with high efficiency. The disadvantage is that the allocated memory capacity is limited. In Linux, 8192 K (8 M, providing ulimit-s viewing) is supported ).
In this storage mode, variable memory is automatically allocated and released for convenient calling. However, the stack capacity is limited. When the corresponding range ends, local variables cannot be used any more.
4. In the heap area, some operation objects can be determined only when the program is running (for example, the employee name in a struct must be manually input by the user and the memory size must be known only after the user input is complete ), in this way, the compiler cannot allocate space in advance during compilation. It can only be allocated when the program is running, also known as dynamic allocation. When the program runs, it uses the malloc function to apply for any amount of memory. The programmer is responsible for releasing the memory (using the free function ). The life cycle of dynamic memory is determined by us. It is flexible to use, but there are many problems.