The difference between heap and stack is mainly the following five points:
1, Management mode: For the stack, is automatically managed by the compiler, without our manual control; for the heap, release work is controlled by the programmer, and it is easy to generate memory leak.
2. Application Size:
A stack is a data structure that extends to a low address and is a contiguous area of memory. This sentence means that the top of the stack address and the maximum capacity of the stack is the system pre-defined, is a compile-time determination of the constant, if the request space exceeds the stack's remaining space, will prompt overflow (overflow). Therefore, the space available from the stack is small.
A heap is a data structure that extends to a high address and is a discontinuous area of memory. This is due to the fact that the system is a free memory address stored by the linked list, which is naturally discontinuous, while the traversal direction of the list is addressed by the low address to the high address. The size of the heap is limited by the valid virtual memory in the computer system. Thus, the space of the heap is more flexible and relatively large.
3. Fragmentation issues:
For the heap, frequent new, delegate is bound to cause memory space discontinuity, resulting in a large number of fragments, so that program efficiency is reduced. For the stack, there is no problem, because the stack is advanced out of the queue, they are so one by one correspondence, so that there will never be a memory block from the middle of the stack pop.
4. Distribution method:
Stacks are allocated in 2 ways: static allocation and dynamic allocation. Static allocations are done by the compiler, such as the allocation of local variables. The dynamic allocation is assigned by the ALLOCA function, but the dynamic allocation of the stack is different from the heap, and his dynamic allocation is released by the compiler without our manual implementation.
The heap is dynamically allocated and there are no statically allocated heaps.
5. Allocation Efficiency:
Stack is the data structure provided by the machine system, the computer will support the stack at the bottom, allocate the address of the special register storage stack, and the stack stack has special instruction execution, which determines the efficiency of the stack is high. The heap is provided by the C + + function library, and its mechanism is very complex.
Differences in heap and stack in iOS