Different stacks in C language

1.Management method: For the stack, it is managed automatically by the compiler, without our manual control; for the heap In other words, the release work is controlled by the programmer and is easy to produce a memory leak.

2. Space size : Generally speaking, under 32-bit system, heap memory can reach 4G space from this corner. There is almost no limit to the amount of heap memory. But for the stack, there is usually a certain amount of space. Size, of course, we can modify

3. Fragmentation problem : For the heap, frequent new/delete will inevitably cause memory space discontinuity. This results in a large amount of debris, which reduces the efficiency of the program. For the stack, there is no such problem, because For the stack is the advanced out queue, they are so one-to-one correspondence, so that there is never an inner The save block pops up from the middle of the stack. Before he pops up, the contents of the post on the back of the stack have been popped up

4. Growth direction : For the heap, the growth direction is upward. That is, the party that increases toward the memory address For the stack, its growth direction is downward, which is increasing toward the memory address.

5. Distribution method : Heaps are dynamically allocated, there is no statically allocated heap. There are 2 ways to distribute the stack: static State allocation and dynamic allocation. Static allocation is done by the compiler, such as the allocation of local variables. Dynamic allocation Assigned by the alloca function, but the dynamic allocation of the stack is different from the heap, and his dynamic allocation is The compiler releases it without us having to do it manually.

6. Distribution efficiency: The stack is the data structure provided by the machine system, and the computer will support the stack at the bottom: Assign a special register to store the address of the stack, and push the stack to have a special instruction to execute, which determines the stack. The efficiency is relatively high. The heap is provided by the C/C++ function library, and its mechanism is very complicated, for example, to divide With a piece of memory, the library function will search the heap memory for a sufficient amount of space according to a certain algorithm, if there is not enough space (may be Due to too much memory fragmentation, it is possible to call system functions to increase the memory space of the program data segment. There is a chance to get enough memory and then return. Obviously, the heap is much less efficient than the stack.