(1) Management method: The resource in the heap is controlled by programmer (through Malloc/free, New/delete, easy to generate memory leak), and the stack resource is automatically managed by the compiler. (2) system response: For the heap, the system has a record of the free memory address of the linked list, when the system received a program request, traverse the list, looking for the first space larger than the application space of the heap node, delete the idle node linked list of the node, The node space is allocated to the program (most systems record the size of this allocation at the first address of the memory space, so that delete can properly free up the memory space, and the system will re-place the extra parts into the idle list). For the stack, as long as the remaining space of the stack is larger than the requested space, the system will allocate memory for the program, or the exception of the stack space overflow error. (3) Space size: The heap is a discontinuous area of memory (because the system uses a linked list to store the free memory address, nature is not continuous), the size of the heap is limited by the effective virtual memory in the computer system (32-bit machine is theoretically 4G size), so the heap space is more flexible, larger. Stack is a contiguous area of memory, the size of the operating system is scheduled, Windows stack size is 2M (there is 1M, at compile time, VC can be set). (4) Fragmentation problem: for heaps, frequent new/delete can result in large amounts of memory fragmentation and reduced program efficiency. For stacks, it is an advanced post-out (FIRST-IN-LAST-OUT) structure that corresponds to and from one by one and does not produce fragmentation. (5) Growth direction: heap upward, increase to high address direction, stack downward, to low address direction growth. (6) Allocation method: The heap is dynamically allocated (no statically allocated heap). Stacks have static allocations and dynamic allocations, static allocations are done by compilers (such as function local variables), and dynamic allocations are allocated by the ALLOCA function, but the dynamically allocated resources of the stack are automatically freed by the compiler without the programmer's implementation. (7) Allocation efficiency: The heap is provided by the C + + function library, the mechanism is complex, so the heap efficiency is much lower than the stack. The stack is the data structure provided by the machine system, the computer supports the stack at the bottom, allocates the special register storage stack address, provides the stack operation specialized instruction.
C + +: Differences in heap and stack