다음을 통해 공유


오류: stack-buffer-overflow

삭제자 오류 해결: 스택 버퍼 오버플로

스택 버퍼 오버플로는 C 또는 C++에서 여러 가지 방법으로 발생할 수 있습니다. 간단한 다시 컴파일을 통해 catch할 수 있는 이 오류 범주에 대한 몇 가지 예제를 제공합니다.

예제 - 스택 버퍼 오버플로

// example1.cpp
// stack-buffer-overflow error
#include <string.h>

int main(int argc, char **argv) {
    char x[10];
    memset(x, 0, 10);
    int res = x[argc * 10];  // Boom! Classic stack buffer overflow

    return res;
}

이 예제를 빌드하고 테스트하려면 Visual Studio 2019 버전 16.9 이상 개발자 명령 프롬프트에서 다음 명령을 실행합니다.

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

결과 오류

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

예제 - 스택 버퍼 수학

// example2.cpp
// stack-buffer-overflow error
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

int main(int argc, char **argv) {
    assert(argc >= 2);
    int idx = atoi(argv[1]);
    char AAA[10], BBB[10], CCC[10];
    memset(AAA, 0, sizeof(AAA));
    memset(BBB, 0, sizeof(BBB));
    memset(CCC, 0, sizeof(CCC));
    int res = 0;
    char *p = AAA + idx;
    printf("AAA: %p\ny: %p\nz: %p\np: %p\n", AAA, BBB, CCC, p);

    return *(short*)(p) + BBB[argc % 2] + CCC[argc % 2];  // Boom! ... when argument is 9
}

이 예제를 빌드하고 테스트하려면 Visual Studio 2019 버전 16.9 이상 개발자 명령 프롬프트에서 다음 명령을 실행합니다.

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

결과 오류 - 스택 버퍼 수학

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

예제 - 스택에서 부적절한 다운 캐스팅

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

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

int main(void) {

    Parent p;
    Child *c = (Child*)&p;
    c->extra_field = 42;  // Boom !

    return (c->extra_field == 42);
}

이 예제를 빌드하고 테스트하려면 Visual Studio 2019 버전 16.9 이상 개발자 명령 프롬프트에서 다음 명령을 실행합니다.

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

결과 오류 - 스택에서 부적절한 다운 캐스트

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

참고 항목

AddressSanitizer 개요
AddressSanitizer 알려진 문제
AddressSanitizer 빌드 및 언어 참조
AddressSanitizer 런타임 참조
AddressSanitizer 섀도 바이트
AddressSanitizer 클라우드 또는 분산 테스트
AddressSanitizer 디버거 통합
AddressSanitizer 오류 예제