次の方法で共有


エラー: heap-buffer-overflow

Address Sanitizer のエラー: ヒープ バッファー オーバーフロー

この例では、ヒープに割り当てられたオブジェクトの境界の外部でメモリ アクセスが発生したとき発生するエラーを示します。

例 - クラシック ヒープ バッファー オーバーフロー

// 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 エラーの例