在Windows系統中配置Google AddressSanitizer

Google AddressSanitizer簡介

AddressSanitizer (ASan) 是 C 和 C++ 的內存錯誤檢測軟件,它能夠檢測:html

  • 釋放指針後繼續使用
  • 堆緩衝區溢出
  • 棧緩衝區溢出
  • 全局緩衝區溢出
  • 返回後繼續使用
  • 在範圍以外繼續使用
  • 初始化順序的bug
  • 內存泄漏

在 Windows 系統中,能夠在 LLVM 和 MSVC 中進行使用。git

Visual Studio 2019的配置

先上兩個連接:github

https://devblogs.microsoft.com/cppblog/addresssanitizer-asan-for-windows-with-msvc/windows

https://devblogs.microsoft.com/cppblog/asan-for-windows-x64-and-debug-build-support/#16-9-preview-3-and-later工具

根據這兩個連接進行安裝配置應該問題不大,Visual Studio 16.9 Preview 3及其之後的版本不須要額外手動配置連接庫,建議安裝這個版本以後的軟件,能省點事情,這樣就只須要配置一下項目的屬性便可,下面是簡單的配置及測試結果。visual-studio

VS2019.png

AddressSaniziter.png

CLion中的配置

先放個CLion的官方教程連接測試

配置ToolChains

CLion 中的配置稍微複雜一點,首先配置CLion的工具鏈,添加一個新的 Visual Studio的配置,正常狀況下添加配置的時候會自動識別,可是個人社區版VS2019在CLion 2020.3這個版本下是沒法自動識別的。我嘗試過手動指定環境也沒有識別,幾經折騰後我放棄了,轉頭就安裝了個企業版😂。這下仍是沒法自動識別,可是手動指定環境後就識別了,Architecture根據須要設定便可,Platform建議默認,Version根據須要設定便可,編譯器直接使用自動檢測的配置便可,若是安裝了 Clang的編譯器也能夠手動指定爲Clang的編譯器,不過在後面配置CMakeLists.txt的時候須要更改連接庫的路徑爲Clang對應的目錄。ui

CLion_VS2019.png

配置CMake選項

CLion_VS2019_02.png

編寫CMakeLists.txt

這個CMakeLists.txt文件會遍歷所在目錄下的全部 .cpp 源文件,每一個源文件建立一個單獨的可執行項目google

cmake_minimum_required(VERSION 3.17)
project(LeetCode VERSION 1.0.0 LANGUAGES CXX)

# Retrieve all cpp file in the current cmake source directory
file(GLOB SOURCES RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.cpp)

# debug message
function(debug_message MESSAGE)
    message("==============================")
    message(${MESSAGE})
    message("==============================")
endfunction()

if (CMAKE_BUILD_TYPE STREQUAL "Debug")
    set(BuildType "dbg_")
endif ()

# add all to executable target
foreach (SRC IN LISTS SOURCES)
    string(REGEX REPLACE "(^.+)\\.(.+$)" \\1 TMP_SRC ${SRC})
    string(REPLACE " " "_" TARGET_NAME ${TMP_SRC})
    add_executable(${TARGET_NAME} ${SRC})
    target_include_directories(${TARGET_NAME} PRIVATE include)
    if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC")
        target_compile_options(${TARGET_NAME} PRIVATE -fsanitize=address)
        # set link directories
        target_link_directories(${TARGET_NAME} PRIVATE
                "D:/Microsoft Visual Studio/2019/Enterprise/VC/Tools/MSVC/14.28.29333/lib/x64/")
        target_link_libraries(${TARGET_NAME} PRIVATE
                clang_rt.asan_${BuildType}dynamic-x86_64
                clang_rt.asan_${BuildType}dynamic_runtime_thunk-x86_64)
        target_link_options(${TARGET_NAME} PRIVATE
                /wholearchive:clang_rt.asan_${BuildType}dynamic_runtime_thunk-x86_64.lib)
    endif ()
endforeach ()

測試

運行的時候可能會失敗,把缺失的動態庫拷貝到可執行文件目錄下便可,不想拷貝就在環境變量裏面添加與Visual Studio工具鏈匹配的路徑也可。例如,我上面工具鏈設置的是amd64,CLion自動檢測到的編譯器是「D:\Microsoft Visual Studio\2019\Enterprise\VC\Tools\MSVC\14.28.29910\bin\Hostx64\x64\cl.exe」,這時候把「D:\Microsoft Visual Studio\2019\Enterprise\VC\Tools\MSVC\14.28.29910\bin\Hostx64\x64\」這個路徑添加到環境變量中重啓CLion便可正常運行。debug

CLion_VS2019_03.png

本文博客地址

相關文章
相關標籤/搜索