다음을 통해 공유


오류: 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 오류 예제