Tuesday, July 26, 2011

C++: Stack and heap


Well, it's beren over a year since posting this to the blog...

Last time, we looked at dynamic memory and consequences of memory leak. This
time, we'll go over a short note on stack versus heap memory.

Stack, as you'll learn about it a bit more later, works like a stack of
dishes. Whatever you store on top will be the first one to pop off. In
programming, this memory location is used to hold variables declared at
compile time - that is, variables that programmers put on source code, which
has a name and content. For instance, a declaration like:
int i = 5;
Would be stored on the stack, since it'll be converted to whatever the
program would use when the compiler is run.

Usually, a stack grows from bottom to top i.e. 1, 2, 3, etc.

As opposed to stack, a heap stores variables stored dynamically. For
example, the car dealership we saw last time would have the car info stored
on a heap. Whenever you use the keyword "new" and "delete", whatever that
was declared would be stored on a heap (new) and removed (delete) from heap.
By the way, the amount of heap used will depend on how many dynamic items
(or objects) you'll be using; and be careful: when you forget to delete
dynamic memory, the operating system (system software) would not take the
memory back and the program will create memory leaks!

Usually, a heap's memory address grows from top to bottom i.e. 5, 4, 3, etc.
For most cases, the stack and heap addresses (memory locations) would not
touch each other.

Quick review: Where would the following two variables be stored:
A. string name = new string[2];
Since the keyword "new" was used, it'll be stored on heap.

B. string my_name = {"Joseph", "Riverside"};
Since the variable was declared without usage of dynamic memory keywords,
it'll be stored on stack.

There is actually a third memory type, but I will not touch it yet - that's
reserved for later.

No comments:

Post a Comment