Address Sanitizer

Track down memory violations in your code.


The Address Sanitizer, or ASan, is an LLVM based tool for C languages and Swift that finds memory corruptions and other memory errors at runtime. Memory errors can lead to unpredictable behavior and can be hard to reproduce consistently.

How ASan Works

The Address Sanitizer replaces the malloc and free functions with custom implementations that allow regions surrounding the requested memory to be checked for invalid access.

When the malloc function is called, it allocates the requested amount of memory and marks the surrounding regions as off-limits. When the free function is called, it marks the region as off-limits and adds it to a quarantine queue, which delays when that memory can be reused by the malloc function. All memory accesses in the code are transformed by the compiler according to Listing 1.

Listing 1

Address Sanitizer memory access pseudocode

// Before
*address = ...;  // or: ... = *address;

// After
if (IsMarkedAsOffLimits(address)) {
*address = ...;  // or: ... = *address;

When code is run with ASan enabled, any access to a memory region that's off-limits results in an error reported by the Address Sanitizer.

Performance Impact

Running your code with Address Sanitizer checks enabled typically results in CPU slowdown of 2⨉ to 5⨉, and an increase in memory usage by 2⨉ to 3⨉. You can improve memory utilization by compiling at the -O1 optimization level.

For most use cases, the overhead introduced by the Address Sanitizer should be acceptable for daily use during development—in fact, you may not even notice any slowdown.


As a runtime diagnostic, the Address Sanitizer can only detect memory errors that are encountered during program execution. To exercise the full extent of your code, incorporate comprehensive unit tests.

The Address Sanitizer cannot detect memory leaks, access to uninitialized memory, or integer overflow. However, you can use ASan in addition to TSan, UBSan, and Instruments to find additional issues.


First Steps

Enabling the Address Sanitizer

Configure your Xcode scheme to check for memory violations at runtime.

Address Sanitizer Checks

Use of Deallocated Memory

Detects when memory is used after being deallocated.

Deallocation of Deallocated Memory

Detects when memory is freed after being deallocated.

Deallocation of Nonallocated Memory

Detects when nonallocated memory is freed.

Use of Stack Memory After Function Return

Detects when stack variable memory is accessed after its declaring function returns.

Use of Out-of-Scope Stack Memory

Detects when variables are accessed outside of their declared scope.

Overflow and Underflow of Buffers

Detects when memory is accessed outside of a buffer’s boundaries.

Overflow of C++ Containers

Detects when a C++ container is accessed outside its bounds.