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 next course. For now, we just need to understand an important consideration when we’re using references or pointers to objects created in our function.
Let's demonstrate the problem with a simple program:
#include <iostream>
using namespace std;
int* GetNumber(){
int Number{1};
return &Number;
}
int main(){
int* Result{GetNumber()};
cout << "Result: " << *Result;
}
We might expect this to log out 1
, but that is not the case:
Result: -858993460
The compiler should give us a warning that we might have been doing something wrong on our return
statement:
Address of stack memory associated with local variable Number returned
Let's delve a little deeper into this warning, as we should 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.
Within our call to GetNumber()
, we are allocated memory to store the int
we created. We then returned that memory address to our main
function:
However, stack frames are an automated form of memory management. When the function ends, its stack frame, and all the objects stored within it are destroyed.
We can see this by using a custom type with a destructor:
#include <iostream>
using namespace std;
struct SomeType {
int Value{1};
~SomeType(){ cout << "Destroying\n"; }
};
SomeType* GetObject(){
SomeType SomeObject;
return &SomeObject;
}
int main(){
SomeType* Result{GetObject()};
cout << "Result: " << Result->Value;
}
Destroying
Result: -858993460
When we have a pointer or reference to an object, and that object is then deleted, the pointer is no longer useful. It is sometimes referred to as a dangling pointer or dangling reference.
If we attempt to use a dangling pointer or reference, our program's behavior becomes undefined. This often leads to unpredictable results, and may cause crashes or other serious issues.
This is because the memory our object was using is freed up for other purposes, meaning we no longer know what will be stored there by the time we use our pointer or reference.
Previously, we've been creating and returning local variables by value without issues. When we return a value from a function, that value is typically copied or moved to the calling function's stack frame or another appropriate location.
When the thing we returned was the value, everything worked 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.
In C++, objects have different lifetimes depending on how they're created. This concept is known as storage duration. The local variables we've been using in functions have what's called automatic storage duration - they're automatically created when the function is called and destroyed when it ends.
However, there are other storage durations in C++:
For now, we're primarily concerned with automatic storage duration and its implications. When we need an object to last longer than a single function call, we have several options:
main
functionIn the next course, we'll delve deeper into memory management and explore how to control object lifetimes more precisely. This will include techniques for dynamic allocation and smart pointers, which give us more flexibility in managing object lifetimes.
In this lesson, we briefly introduced the concept of storage durations, and how memory allocated on the stack is automatically freed when the stack frame is destroyed.
In particular, we covered the implications this has for objects returned by pointer or reference from functions, and how improper usage can cause memory problems.
In the next chapter, we introduce polymorphism - a key technique that lets us ramp up the complexity of our program, without necessarily making our code more complex. We’ll cover:
Learn about an important consideration when returning pointers and references from functions
Become a software engineer with C++. Starting from the basics, we guide you step by step along the way