錯誤: double-free

位址清理程式錯誤:已釋放記憶體的解除配置

在 C 中,您可以錯誤地呼叫 free 。 在 C++ 中,您可以多次呼叫 delete 。 在這些範例中,我們會顯示 、 freeHeapCreate 的錯誤 delete

範例 C++ - double operator delete

// example1.cpp
// double-free error
int main() {

    int *x = new int[42];
    delete [] x;

    // ... some complex body of code

    delete [] x;
    return 0;
}

若要建置及測試此範例,請在 Visual Studio 2019 16.9 版或更新版本的 開發人員命令提示字元 中執行下列命令:

cl example1.cpp /fsanitize=address /Zi
devenv /debugexe example1.exe

產生的錯誤 - double operator delete

Screenshot of debugger displaying double-free error in example 1.

範例 'C' - double free

// example2.cpp
// double-free error
#include <stdlib.h>
#include <string.h>

int main(int argc, char** argv) {

    char* x = (char*)malloc(10 * sizeof(char));
    memset(x, 0, 10);
    int res = x[argc];
    free(x);

    // ... some complex body of code

    free(x + argc - 1);  // Boom!
    return res;
}

若要建置及測試此範例,請在 Visual Studio 2019 16.9 版或更新版本的 開發人員命令提示字元 中執行下列命令:

cl example2.cpp /fsanitize=address /Zi
devenv /debugexe example2.exe

產生的錯誤 - double free

Screenshot of debugger displaying double-free error in example 2.

範例 - Windows HeapCreate double HeapFree

// example3.cpp
// double-free error
#include <Windows.h>
#include <stdio.h>

int main() {
    void* newHeap = HeapCreate(0, 0, 0);
    void* newAlloc = HeapAlloc(newHeap, 0, 100);

    HeapFree(newHeap, 0, newAlloc);
    HeapFree(newHeap, 0, newAlloc);
    printf("failure\n");
    return 1;
}

若要建置及測試此範例,請在 Visual Studio 2019 16.9 版或更新版本的 開發人員命令提示字元 中執行下列命令:

cl example3.cpp /fsanitize=address /Zi
devenv /debugexe example3.exe

產生的錯誤 - Windows HeapCreate double HeapFree

Screenshot of debugger displaying double-free error in example 3.

另請參閱

AddressSanitizer 概觀
AddressSanitizer 已知問題
AddressSanitizer 組建和語言參考
AddressSanitizer 執行時間參考
AddressSanitizer 陰影位元組
AddressSanitizer 雲端或分散式測試
AddressSanitizer 偵錯工具整合
AddressSanitizer 錯誤範例