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

Understanding Unreal Engine Memory Allocators

Learn to utilize FMemory and custom allocators to manage heap memory efficiently while adhering to Unreal's specific memory tracking standards.

In this lesson, you will learn how to bypass standard C++ memory management to tap into Unreal Engine’s optimized memory allocators for faster, safer, and tracked heap allocations.

Why Avoid malloc or new?

In standard C++, you might reach for new or malloc to allocate memory on the heap. However, in Unreal Engine, these standard methods are "invisible" to the engine’s internal tracking systems. If you don't use Unreal's allocators, the engine cannot track your memory usage, detect leaks, or perform specialized optimizations like memory pooling.

Using FMemory

The FMemory static class is your primary interface for managing raw heap memory. Instead of using new, you use FMemory::Malloc and FMemory::Free. These functions route your allocation requests through Unreal’s memory management layer, allowing the engine to provide you with stats, profiling data, and protection against fragmentation.

Here is a quick look at how you might allocate and free a block of memory manually:

// Allocate 1024 bytes of memory
void* MyRawBuffer = FMemory::Malloc(1024);

// ... Perform work with the buffer ...

// Free the memory when done
FMemory::Free(MyRawBuffer);

Why Use Custom Allocators?

Beyond just tracking, Unreal uses different memory allocators depending on the situation. For example, some allocators are optimized for small, high-frequency allocations (like TArray elements), while others are designed for large chunks of data. When you use Unreal containers like TArray or TMap, they automatically use these internal allocators (like FMalloc or FMemStack) to ensure your data is stored as efficiently as possible.

When working with raw buffers or performance-critical systems, always prioritize FMemory or Unreal’s container classes. Using these ensures that your custom data is visible to the memory profiling tools we discussed in previous lessons, helping you maintain a lean performance profile. By sticking to these engine-level tools, you ensure that your manual memory management stays compatible with the rest of the engine's lifecycle.

Key Takeaway: Always use FMemory or Unreal’s built-in container classes for heap allocations to ensure your memory usage is tracked, profiled, and optimized by the engine’s internal systems.