🐸Memory Model
Memory Layout
Variables can either be created or destroyed. They can also exists on different locations (i.e the stack, heap or static storage)

Stack vs Heap
Stack
Variables created (i.e allocated) on the stack possess automatic storage duration. This means they are:
allocated when execution enters their scope
deallocated when out of scope
To jog your memory, all the previous variable declarations in Variables and Pointers were all allocated on the stack.
Consider the following example (please ignore the implementation details of Person class for now)
The following output is as shown:

Observe that similar to the Last-In-First-Out (LIFO) behaviour of literal stack data structure, objects are constructed in order of declaration. They are also destroyed in order of reverse order.

Note that the behaviour is tied to scope, objects are destroyed as soon as it exits the scope.

Heap
While the stack is fast, it does suffer from a few limitations:
Size of the objects must be known / determinable at compile time
The lifetime of objects is tied to scope
You can use a new keyword to allocate memory on the heap. Unlike the stack, the heap memory is not tied to scope. It persists until it is explictly deallocated with delete.
Let's take a look at how heap tackles these limitations:

Dangling Pointers
Another common pitfall that programmers often stumble upon is the issue of dangling pointers. This refers to the situation when we try to access memory that already has been deallocated.
The above is an example of undefined behavior. For me, it prints 0 but the C++ standard makes no guarantees about what happens.

It could also potentially print 5, print garbage values or crash through a segmentation fault.
Last updated
Was this helpful?


