Track down memory violations in your code.
- Xcode 7.0+
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
free functions with custom implementations that allow regions surrounding the requested memory to be checked for invalid access.
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.
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.
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.