Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use AddressSanitizer with GCC?

I'm trying to build my project with

g++ -O0 -g -fsanitize=address -fno-omit-frame-pointer

but get lots of errors like:

/home/user/libs/opencv/include/opencv2/core/mat.hpp:715: undefined reference to `__asan_report_load8'

How to compile project with AddressSanitize support?

My gcc version is 4.8.4.

like image 340
mrgloom Avatar asked Jun 22 '16 14:06

mrgloom


People also ask

What is GCC AddressSanitizer?

Address Sanitizer is a tool developed by Google detect memory access error such as use-after-free and memory leaks. It is built into GCC versions >= 4.8 and can be used on both C and C++ codes.

What does GCC Fsanitize do?

This option disables all previously enabled sanitizers. -fsanitize=all is not allowed, as some sanitizers cannot be used together. This option forces GCC to use custom shadow offset in AddressSanitizer checks. It is useful for experimenting with different shadow memory layouts in Kernel AddressSanitizer.

How do I use AddressSanitizer in Windows?

You can turn on ASan for an MSBuild project by right-clicking on the project in Solution Explorer, choosing Properties, navigating under C/C++ > General, and changing the Enable Address Sanitizer (Experimental) option. The same approach can be used to enable ASan for MSBuild Linux projects.

What is AddressSanitizer error?

AddressSanitizer is a fast memory error detector. It consists of a compiler instrumentation module and a run-time library. The tool can detect the following types of bugs: Out-of-bounds accesses to heap, stack and globals.


3 Answers

You need to add -fsanitize=address to compiler flags (both CFLAGS and CXXFLAGS) and linker flags (LDFLAGS). You've probably added it to your compiler flags only.

Note that using explicit -lasan option has been widely discouraged by ASan developers (e.g. here) as it misses some other important linker flags. The only recommended way to link is to use -fsanitize=address.

As a side note, for more aggressive verification flags check Asan FAQ (look for "more aggressive diagnostics").

like image 152
yugr Avatar answered Sep 22 '22 15:09

yugr


Make sure you have libasan installed. For example, in Fedora:

dnf install libasan libasan-static

like image 35
Jonny Avatar answered Sep 25 '22 15:09

Jonny


You need to add the switch -lasan -fsanitize=address to your both your compile and link command line to link the correct library.

Note: the original answer -lasan is outdated and should not be used, as per comments

like image 27
Smeeheey Avatar answered Sep 24 '22 15:09

Smeeheey