【C++】内存泄漏排查

2023-12-28 19:46:01

前言

内存泄漏影响程序的稳定性运行,并且在程序运行过程中,并不会报错误,需要借助专用的内存泄露工具进行检测。
工具: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

文章来源:https://blog.csdn.net/xi_shui/article/details/135276213
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。