These two areas of memory are optimized for different use cases.
The stack is optimized for the case when objects are freed in FIFO order, that is, new objects are always allocated in front of old objects. Because of this, memory can be allocated and freed up quickly by simply supporting a gigantic array of bytes, and then giving or pulling out bytes at the end. Since the memory needed to store local variables for function calls is always restored in this way (since the functions always finish executing in the reverse order from which they were called), the stack is a great place to allocate this kind of memory.
However, the stack is not suitable for other types of distribution. You cannot easily free memory allocated from the stack, which is not the most recently allocated block, as this leads to "gaps" in the stack and complicates the logic of determining where bytes are available. For these types of distributions, when the lifetime of an object cannot be determined from the moment the object was allocated, the heap is the best place to store things. There are many ways to implement the heap, but most of them somehow rely on the idea of storing a giant table or a linked list of blocks that are distributed in a way that makes it easy to find suitable chunks of memory for customer feedback. When the memory is freed, it is then added back to the table or linked list, and perhaps some other logic is used to compact the blocks with other blocks. Due to this overhead from the search time, the heap is usually much, much slower than the stack. However, the heap can perform distributions in templates that are usually not suitable for the stack, so they are usually present in the program.
Interestingly, there are other ways of allocating memory that fall somewhere between them. One general allocation method uses something called an “arena,” where one large piece of memory is allocated from the heap, which is then split into smaller blocks, for example, on the stack. This gives the advantage that the distributions from the arena are very fast if the distributions are sequential (for example, if you are going to select many small objects that all live about the same length), but the objects can survive any call to a certain function. and this is just a small sample of what is possible, but should clearly show that memory allocation is associated with trade-offs. You just need to find a dispenser that suits your specific needs.
templatetypedef
source share