Understanding the heap and the stack

Initially messing around with Swift, memory management was a bit foreign to me because Swift magically handles the memory for us. But in c++ that isn't the case. We have to use something called the heap and something called the stack. And, if we're not careful and make mistakes, we can cause what's infamously known as a "stack overflow". 

First, both the stack and the heap are used for dynamic memory allocation and both are stored on your computer's random access memory (RAM).

The stack is very fast. It stored directly to memory, which makes it quite fast. It's allocated when a program is run. Essentially, you write a function that declares value x and then you have code that continues to use value x in the stack. It isn't until value x is returned that its place in the stack is freed and something new can use that for memory. So, the risk is when a programmer forgets to free it up and you use all the spots in the stack memory and it "overflows" -- common in the 80s and before but far less common now because our memory capacities have expanded. Stack follows last-in-first-out order and you access it using pointers in your code. 

The heap is a bit slower because you're accessing the memory at run time, but it's got a lot more memory to work with (especially these days). The heap is hugely valuable because unlikely value x on the stack that was constantly being adjusted so it could have been initiated at 10 but then doubled to 20 on the next line of code, the heap lets you reference a value that remains the same regardless of where you access it in your program. Think of it as a global memory pool. So, I could initiate a value y on the heap that was set to 50 states in the United States. Well, I could write a program that calculated the number of states in the United States depending on the year. I could write a function for the Civil War that only returned northern states or a function for the Louisiana Purchase that calculated the number of states against the current 50 United States. But, 50, as the value of the number of United States could be accessed unchanged by by Civil War function and my Louisiana Purchase function. We could even use the same value y for our 50 states if we wanted to write a function that returned the number of states that would remain if California succeeded. 

Aside from access control using pointers, it makes sense to use the stack when you know exactly what you want to allocate and it's not too too big but the heap is a better call if you're not sure of how much data you're actually going to need to store or if you anticipate it being a ton of data.