内存泄漏影响程序的稳定性运行,并且在程序运行过程中,并不会报错误,需要借助专用的内存泄露工具进行检测。
工具:CLion and AddressSanitizer
#include <iostream>
using namespace std;
int main() {
char *c = new char[2];
*c = '1';
delete c;
return 0;
}
CMakeLists.txt 添加参数 -fsanitize=addres
cmake_minimum_required(VERSION 3.17)
project(code)
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -fsanitize=address")
set(CMAKE_CXX_STANDARD 14)
add_executable(code main.cpp)
=================================================================
==3026==ERROR: AddressSanitizer: alloc-dealloc-mismatch (operator new [] vs operator delete) on 0x602000000010
#0 0x7f19d988e025 in operator delete(void*, unsigned long) (/usr/lib/x86_64-linux-gnu/libasan.so.5+0x111025)
#1 0x561bc11fd2f3 in main /data/code/main.cpp:7
#2 0x7f19d93cd0b2 in __libc_start_main (/usr/lib/x86_64-linux-gnu/libc.so.6+0x240b2)
#3 0x561bc11fd1cd in _start (/data/code/cmake-build-debug/code+0x11cd)
0x602000000010 is located 0 bytes inside of 2-byte region [0x602000000010,0x602000000012)
allocated by thread T0 here:
#0 0x7f19d988cb47 in operator new[](unsigned long) (/usr/lib/x86_64-linux-gnu/libasan.so.5+0x10fb47)
#1 0x561bc11fd29e in main /data/code/main.cpp:5
#2 0x7f19d93cd0b2 in __libc_start_main (/usr/lib/x86_64-linux-gnu/libc.so.6+0x240b2)
SUMMARY: AddressSanitizer: alloc-dealloc-mismatch (/usr/lib/x86_64-linux-gnu/libasan.so.5+0x111025) in operator delete(void*, unsigned long)
==3026==HINT: if you don't care about these errors you may set ASAN_OPTIONS=alloc_dealloc_mismatch=0
==3026==ABORTING