Linux uses asan to troubleshoot C/C++ memory leaks

Linux uses asan to troubleshoot C/C++ memory leaks

If you need to reprint, please indicate the source: https://blog.csdn.net/itas109
Technical exchange: 129518033

environment:

OS: Ubuntu 20.04 / CentOS 7
编译器: gcc/g++ 9.4.0

1. Using AScan

ASAN was originally a feature of LLVM, and was later added to gcc4.8 as a part of gcc, but it does not support symbol information, and cannot display the function and line number of the problem. Starting from 4.9, gcc supports all features of AddressSanitizer.

2. Test code

main.cpp

int main()
{
	char* s = new char[256];
	return 0;
}

CMakeLists.txt

cmake_minimum_required(VERSION 2.8.12)

project(main)

# check memory leak
set(CMAKE_CXX_FLAGS "-g -fsanitize=address")

add_executable( ${PROJECT_NAME} main.cpp)

g++ compile

$ g++ -fsanitize=address -g main.cpp -o main

cmake compile

$ cmake -B bin
$ cmake --build bin

test

$ export LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libasan.so.5

$ ./main

=================================================================
==2499561==ERROR: LeakSanitizer: detected memory leaks

Direct leak of 256 byte(s) in 1 object(s) allocated from:
    #0 0x7fadbeb0f787 in operator new[](unsigned long) ../../../../src/libsanitizer/asan/asan_new_delete.cc:107
    #1 0x56386698619e in main /root/memoryLeakTest/main.cpp:3
    #2 0x7fadbe4e6082 in __libc_start_main ../csu/libc-start.c:308

SUMMARY: AddressSanitizer: 256 byte(s) leaked in 1 allocation(s).

3. centos7 upgrade gcc support ascan

The default gcc version of centos7 is 4.8.5

Download the offline installation package

sudo yum update
sudo yum install centos-release-scl
sudo yum install --downloadonly --downloaddir=devtoolset9 devtoolset-9 
sudo yum install --downloadonly --downloaddir=devtoolset9 devtoolset-9-libasan-devel libssan

Install

cd devtoolset9
sudo rpm -ivh devtoolset-9-*

use

scl enable devtoolset-9 bash

License

License under CC BY-NC-ND 4.0: Attribution-Noncommercial Use-No Derivatives

If you need to reprint, please indicate the source: https://blog.csdn.net/itas109
Technical exchange: 129518033

Guess you like

Origin blog.csdn.net/itas109/article/details/130303451