錯誤: heap-buffer-overflow

位址清理程式錯誤:堆積緩衝區溢位

這個範例示範當記憶體存取發生在堆積設定物件界限外時所產生的錯誤。

範例 - 傳統堆積緩衝區溢位

// example1.cpp
// heap-buffer-overflow 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 * 10];  // Boom!

    free(x);
    return res;
}

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

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

產生的錯誤

Screenshot of debugger displaying heap-buffer-overflow error in example 1.

範例 - 不正確的向下轉換

// example2.cpp
// heap-buffer-overflow error
class Parent {
public:
    int field;
};

class Child : public Parent {
public:
    int extra_field;
};

int main(void) {
    Parent *p = new Parent;
    Child *c = (Child*)p;  // Intentional error here!
    c->extra_field = 42;

    return 0;
}

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

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

產生的錯誤 - 不正確的向下轉換

Screenshot of debugger displaying heap-buffer-overflow error in example 2.

範例 - 將 strncpy 串入堆積

// example3.cpp
// heap-buffer-overflow error
#include <string.h>
#include <stdlib.h>

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

    char *hello = (char*)malloc(6);
    strcpy(hello, "hello");

    char *short_buffer = (char*)malloc(9);
    strncpy(short_buffer, hello, 10);  // Boom!

    return short_buffer[8];
}

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

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

產生的錯誤 - 將 strncpy 串入堆積

Screenshot of debugger displaying heap-buffer-overflow error in example 3.

另請參閱

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