Stack And Heap, What Are These?

Asked By 0 points N/A Posted on -
qa-featured

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?

SHARE
Answered By 10 points N/A #324223

Stack And Heap, What Are These?

qa-featured

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.

Login/Register to Answer

Related Questions