Course contentsShow
← Unreal Engine Game Development
Lesson 186 of 8803. C++ and UObject ArchitectureFree lesson

Debugging Memory Leaks and Dangling Pointers

Utilize Unreal’s built-in memory diagnostic tools and visualizers to identify and resolve common memory management errors within your C++ codebase.

In this lesson, you will learn how to leverage Unreal Engine’s internal diagnostic tools to track down memory leaks and dangling pointers before they crash your game.

The "Dangling" Mystery

A dangling pointer occurs when you hold a memory address to a UObject that has already been garbage collected. While TWeakObjectPtr is your best defense, sometimes bugs slip through the cracks. To find them, we use the Console Command system, which acts as a window into the engine's memory state.

Using Memory Visualizers

When you suspect a leak (where objects aren't being garbage collected) or a dangling pointer (which usually causes an access violation crash), open your console (press ~ in the editor) and use these built-in tools:

  1. obj list: This is your primary diagnostic. Typing obj list class=MyClassName will print every instance of that class currently alive in memory. If you close a UI menu but see the object count for that class continuing to rise, you have confirmed a memory leak.
  2. obj refs: If you find an object that should have been destroyed, use obj refs name=MyObjectName. This command lists everything that currently holds a reference to that object, revealing exactly why the Garbage Collector is prevented from cleaning it up.
  3. memreport -full: If the memory usage of your project is ballooning, this command generates a text file in your Saved/Logs folder. It provides a deep dive into memory allocations, allowing you to compare snapshots over time to find where the "growth" is happening.

Identifying the Culprit

If your game crashes with an access violation, it is likely a dangling pointer. Wrap your risky pointer access in a check to gain immediate feedback:

// Instead of accessing directly, check validity first
if (MyWeakPointer.IsValid())
{
    MyWeakPointer->DoSomething();
}
else
{
    UE_LOG(LogTemp, Warning, TEXT("Dangling pointer detected! Object is gone."));
}

By combining these log outputs with TWeakObjectPtr checks, you can turn a "mysterious crash" into a clear, traceable path toward the object that is overstaying its welcome.

Key Takeaway: Use obj list to monitor object counts and obj refs to investigate why specific objects are refusing to be garbage collected.