Dangling Pointers and References

Learn about an important consideration when returning pointers and references from functions

Ryan McCombe
Updated

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.

Stack Memory

In the introductory lessons, we covered the idea of the stack, and how our functions each create stack frames.

The Call Stack and Debugging Functions

An introduction to how our function calls create a call stack, and how we can navigate it in a debugger.

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

What Are Dangling Pointers and References?

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.

Storage Durations

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++:

  1. Static storage duration: Objects exist for the entire run of the program.
  2. Thread storage duration: Each thread has its own copy of the object.
  3. Dynamic storage duration: The programmer controls when objects are created and destroyed.

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:

  • Create it in the global scope (though this should be used sparingly)
  • Create it inside the main function
  • Make it part of a longer-lived object

Later in the course, we'll cover memory management in more detail, and learn 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.

Summary

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.

Next Lesson
Lesson 34 of 60

Function Overloading

This lesson provides an in-depth look at function overloading in C++, covering its importance, implementation, and best practices

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Safely Returning Pointers and References
How can I safely return a pointer or reference from a function without causing dangling pointers?
Tools for Detecting Dangling Pointers
Are there any tools or compiler flags that can help detect potential dangling pointer issues?
Explaining Dangling Pointers to Junior Developers
How do I explain the concept of dangling pointers to junior developers in my team?
Dangling Pointers in Other Programming Languages
How do other programming languages handle similar issues to dangling pointers?
Best Practices for Managing Object Lifetimes
What are some best practices for managing object lifetimes in complex C++ applications?
Dangling Pointers and RAII
How do dangling pointers relate to the RAII (Resource Acquisition Is Initialization) principle?
Design Patterns to Prevent Dangling Pointers
Are there any design patterns that help prevent dangling pointer issues?
Alternatives to Returning Pointers
What are some alternatives to returning pointers or references from functions?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant