Stack Memory and Heap Memory

227 views

Stack Memory and Heap Memory

In: 1

3 Answers

Anonymous 0 Comments

This is… hard to explain because what it means is different for every programming language and execution environment.

If I had to generalize:

Stack memory is short-term memory space reserved for what I am going to call “methods”. Some languages call them “functions” or “subroutines” but the important thing to note is they are “units” of code that can be executed independently of other units.

When a method is called, a “stack” is usually created for it. Really this just means the computer is setting aside some memory space for it. If a method has stack memory, then the variables it creates tend to get stored in that stack memory. This makes it easy to clean up that memory when the method ends: the computer just stops reserving that memory space and it’s done.

But that can be a problem if the method wants to set up some data other methods will use. If it only had stack memory, there wouldn’t be a way to do this. So there’s also a “heap” memory structure that doesn’t “belong” to any particular method. If a programming language has heap memory, it also has some syntax to let users put data in that memory. So long as it has a way to tell other parts of the program where that data was stored, those parts can also access it. The downside is this is harder to clean up. The program can’t tell when it’s “done” with some memory unless the programmer specifically tells it so. Since the heap belongs to “everybody”, it can be hard in complex programs to be sure every part that uses some data understands it’s been destroyed. Or programmers can lose track of some memory and forget to destroy it, causing the program to “leak” memory as it continuously sets up data structures in memory it doesn’t give back.

There are lots of different ways languages and environments try to handle those problems, which is part of why there are so many different programming languages. There are some details about how the “stack” and “heap” are structure in memory I could have mentioned, but they aren’t important to understanding the basic ideas behind them and are so often different from language to language I don’t think I could be specific *and* general.

You are viewing 1 out of 3 answers, click here to view all answers.