Why do programs have both stack and heap memory?


This Content is from Stack Overflow. Question asked by jem do

I am taking a course on programming languages right now and am having trouble understanding the difference between stack and heap variables and why both are needed in a program.

My textbook says this about “stack-dynamic variables”:

Stack-dynamic variables are those whose storage bindings are created when
their declaration statements are elaborated, but whose types are statically
bound. Elaboration of such a declaration refers to the storage allocation and
binding process indicated by the declaration, which takes place when
execution reaches the code to which the declaration is attached. Therefore,
elaboration occurs during run time.

It also says this about “explicit heap-dynamic variables”

Explicit heap-dynamic variables are nameless (abstract) memory cells that
are allocated and deallocated by explicit run-time instructions written by the
programmer. These variables, which are allocated from and deallocated to the
heap, can only be referenced through pointer or reference variables. The heap
is a collection of storage cells whose organization is highly disorganized due
to the unpredictability of its use.

So my question is: why do we have both? From what I’ve read it seems that both stack variables and heap variables are allocated at runtime, so other than the fact that you need to use special keywords like new in C++ to create heap variables, I’m having trouble understanding the difference. I know that certain data structures like trees and linked lists are created with heap variables, but why is it not possible to create them using stack variables?


This question is not yet answered, be the first one who answer using the comment. Later the confirmed answer will be published as the solution.

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?