N/APosted on - 08/17/2019
While I was learning C++, I came across stack and heap, and the sentence that mostly describes it, would be that memory is allocated in either of them. Though I have a vague idea about it, can someone explain it to me with a little more depth?
Stack And Heap, What Are These?
Yes, memory in a C/C++ program is allocated in either of them. The following would explain in a more detailed fashion.
The stack is basically where a function’s variables and the return address is stored whenever there is a function call. It is a contiguous block of memory where memory allocation and deallocation is done by the compiler itself. The cost of handling this frame (access time etc.) is relatively low compared to a heap because of the definitive details put into it. The main issue with the stack is the shortage of memory because it is of fixed size.
Coming to a Heap, its memory is allocated randomly, that is wherever memory is available, and this memory is allocated during the execution of instructions that are written by programmers especially for dynamic memory allocation. This memory should be manually deallocated, or else it can lead to a memory leak. Handling a heap frame is much costlier, relative to stack because of fragmentation. Accessing a heap is both time-consuming and difficult because heap frames are randomly spread throughout memory and it has to be retrieved every time it’s not there in the cache. But heap has a variable size or more accurately size that is fixed by the user.