Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and medical aesthetics - Do the variables in the main function of C language use a stack with those in other functions?
Do the variables in the main function of C language use a stack with those in other functions?
Stack, but not necessarily a heap. Every time the program runs, a stack is allocated, and the main function is at the bottom of the stack. Then through the call order of different functions, they enter and exit the stack in turn. Heap is the space allocated dynamically by the program, and the space allocated each time is not necessarily continuous.

1) is created on the stack. When the function is executed, the storage units of local variables in the function are created on the stack, and these storage units are automatically released when the function is executed. Stack memory allocation operation is built into the instruction set of the processor and is usually accessed by registers, which is efficient, but the allocated memory capacity is limited.

2) Allocating from the heap, also called dynamic memory allocation. When the program is running, malloc or new is used to apply for any amount of memory, and the programmer is responsible for when to release memory with free or delete. The lifetime of dynamic memory is determined by the programmer himself, so it is very flexible to use.

Compilers generally use stacks to store function parameters, local variables, etc. Implement function call. Sometimes functions have nested calls. At this time, there will be information of multiple functions in the stack, and each function occupies a continuous area. The area occupied by a function is called a frame (). At the same time, the stack is thread independent, and each thread has its own stack. A thread has only one stack, and all functions executed in this thread will use this stack. When the function is called, it will open a part of space at the top of the stack (in essence, it just moves the top of the stack up) to save its own data, including the parameters, return address and local variables of the function. When the function returns, as long as the top of the stack is restored to the state before being called, the space it occupies will be released.

For example, the following simple function call: