Now that we’re working with pointers and references, we need to talk briefly about memory management.
This is a large topic - we have a full chapter dedicated to it in the intermediate course. For now, we just need to understand an important limitation with the way we’ve been creating variables so far.
Let's demonstrate that limitation with a seemingly simple program:
#include <iostream>
using namespace std;
// Note, this returns a pointer
int* GetNumber() {
int Number { 1 };
return& Number;
}
int main() {
int* Result { GetNumber() };
cout << &Result;
}
We might expect this to log out 1
, but that is not the case. In fact, on my machine, it logged out 1654145864
. The number is different every time I run the program.
Hopefully, the compiler would have given us a warning that we might have been doing something wrong.
Let's delve a little deeper into this warning, as it’s important that we understand what’s going on here.
In the introductory lessons, we covered the idea of the stack, and how our functions each create stack frames. Stack frames are a form of memory management.
The parameters and local variables that our functions create are stored within these stack frames.
However, stack frames are an automated form of memory management. When the function ends, its stack frame, and all the memory it used, are released.
This means that if we have a pointer to a variable that is stored in a stack frame, that pointer is only useful as long as that stack frame exists.
Once the corresponding function has ended, the stack frame is gone, and the memory is freed up to be used for other purposes. That means we no longer know what is stored in the memory location our pointer is pointing at.
In the past, we’ve been creating and returning local variables without issues. When we return something from a stack frame, that value gets moved or copied to the stack frame that called our function.
When the thing we returned was the value, everything works as expected.
However, when a pointer (or reference) is returned, that pointer can refer to a memory location that is about to be freed. When that pointer is then used, unpredictable things can happen, as the first example demonstrated.
The objects we create in C++ have a few different options for when their memory is released. The scenarios we're covering here - local variables in functions - are examples of what is commonly called automatic storage duration.
In the next course, we cover memory in more detail. This includes techniques for how we can opt out of this form of automatic memory management when we create a variable.
For now, it’s important we’re aware of this behaviour. When we create variables, we want to create them in a place where they will last as long as they are needed.
If we need a variable to last the full duration of our program, places we can create it include:
main
functionBecome a software engineer with C++. Starting from the basics, we guide you step by step along the way