Operating system: centos8
gcc:8.3.1
Asan is a gcc native memory diagnostic tool that can diagnose common memory problems such as memory out of bounds, illegal access, memory leaks, memory double free, and is several times more efficient than valgrind. It can overcome some problems of valgrind, such as high memory usage. It is a better memory problem analysis tool than valgrind!
1. Preparation:
1. Install the asan development library on the compilation environment
yum install libasan.x86_64
2. Install the asan development library in the operating environment. If the operating environment cannot be connected to the Internet, you can download it with yum first, and then install it on the operating environment
2. Compile
CFLAGS+=-fsanitize=address -fno-omit-frame-pointer -fsanitize-recover=address //Need to be used in conjunction with the environment variable ASAN_OPTIONS=halt_on_error=0
SYSLIB+=-lasan //If you cannot find the library, you also need to add -L plus the library path
3. Run
export ASAN_OPTIONS=halt_on_error=0 //Do not exit when the process detects a memory error
export ASAN_OPTIONS=alloc_dealloc_mismatch=0 //Do not detect memory mismatch, for example, new [] does not match delete point
There are many options for asan, you can set the options of ASAN_OPTIONS according to your needs, and other options can be Baidu by yourself
export LD_PRELOAD=/usr/lib64/libasan.so.5.0.0 //Preload the runtime library and replace the memory allocation function in the system library libc
LD_PRELOAD is an environment variable of the Linux system. It can affect the runtime linker of the program. It allows you to define the dynamic link library that is loaded first before the program runs. This environment variable is necessary because libasan.so. 5.0.0 will replace the implementation of malloc and free functions in libc, so the library needs to be preloaded.
At this point, all the work is completed, just run the program that needs to be tested, and the program will print out the detected memory problem.