C++ Undefined Behavior | "미정의 동작" 완벽 가이드

C++ Undefined Behavior | "미정의 동작" 완벽 가이드

이 글의 핵심

C++ Undefined Behavior에 대한 실전 가이드입니다. 개념부터 실무 활용까지 예제와 함께 상세히 설명합니다.

Undefined Behavior란?

C++ 표준이 동작을 정의하지 않은 코드

// UB 예시
int x;
cout << x << endl;  // 초기화 안된 변수 (UB)

int arr[5];
arr[10] = 0;  // 범위 초과 (UB)

int* ptr = nullptr;
*ptr = 10;  // nullptr 역참조 (UB)

결과:

  • 컴파일러마다 다른 동작
  • 최적화에 따라 다른 동작
  • 예측 불가능

주요 UB 종류

1. 초기화 안된 변수

// ❌ UB
int x;
if (x == 0) {  // UB
    // ...
}

// ✅ 초기화
int x = 0;
if (x == 0) {
    // ...
}

2. 배열 범위 초과

// ❌ UB
int arr[5];
arr[10] = 0;  // 범위 초과

// ✅ 범위 체크
if (index < 5) {
    arr[index] = 0;
}

// ✅ vector 사용
vector<int> v(5);
v.at(10);  // 예외 발생 (UB 아님)

3. nullptr 역참조

// ❌ UB
int* ptr = nullptr;
*ptr = 10;

// ✅ nullptr 체크
if (ptr != nullptr) {
    *ptr = 10;
}

4. 댕글링 포인터

// ❌ UB
int* getPointer() {
    int x = 10;
    return &x;  // 지역 변수 주소 반환
}

int* ptr = getPointer();
*ptr = 20;  // UB

// ✅ 동적 할당 또는 static
int* getPointer() {
    static int x = 10;
    return &x;
}

5. 부호 있는 정수 오버플로우

// ❌ UB
int x = INT_MAX;
x++;  // 부호 있는 오버플로우 (UB)

// ✅ 체크
if (x < INT_MAX) {
    x++;
}

// ✅ 부호 없는 타입 (오버플로우 정의됨)
unsigned int x = UINT_MAX;
x++;  // 0 (UB 아님)

6. 데이터 레이스

// ❌ UB
int counter = 0;

void increment() {
    counter++;  // 여러 스레드에서 (UB)
}

// ✅ mutex 또는 atomic
atomic<int> counter(0);

void increment() {
    counter++;
}

7. 잘못된 캐스팅

// ❌ UB
int x = 10;
double* ptr = reinterpret_cast<double*>(&x);
*ptr = 3.14;  // 타입 위반 (UB)

// ✅ 올바른 캐스팅
double d = static_cast<double>(x);

8. 수정 중인 객체 접근

// ❌ UB
int i = 0;
i = i++;  // 순서 미정의 (UB)

// ✅ 명확한 순서
i++;

실전 예시

예시 1: 범위 체크

class SafeArray {
private:
    vector<int> data;
    
public:
    SafeArray(size_t size) : data(size) {}
    
    int& operator {
        if (index >= data.size()) {
            throw out_of_range("인덱스 초과");
        }
        return data[index];
    }
};

int main() {
    SafeArray arr(5);
    
    try {
        arr[10] = 0;  // 예외 발생
    } catch (const out_of_range& e) {
        cout << e.what() << endl;
    }
}

예시 2: 스마트 포인터

// ❌ 댕글링 포인터
int* ptr = new int(10);
delete ptr;
*ptr = 20;  // UB

// ✅ 스마트 포인터
auto ptr = make_unique<int>(10);
// 자동 해제, 댕글링 방지

예시 3: 초기화 강제

class Widget {
private:
    int value;
    
public:
    // ❌ 초기화 안함
    // Widget() {}
    
    // ✅ 초기화 강제
    Widget() : value(0) {}
    
    // ✅ C++11 멤버 초기화
    // int value = 0;
};

UB 탐지 도구

AddressSanitizer (ASan)

# 컴파일
g++ -fsanitize=address -g program.cpp -o program

# 실행
./program

# 출력: 메모리 오류 상세 정보
int main() {
    int arr[5];
    arr[10] = 0;  // ASan이 탐지
}

UndefinedBehaviorSanitizer (UBSan)

# 컴파일
g++ -fsanitize=undefined -g program.cpp -o program

# 실행
./program
int main() {
    int x = INT_MAX;
    x++;  // UBSan이 탐지
}

ThreadSanitizer (TSan)

# 컴파일
g++ -fsanitize=thread -g program.cpp -o program
int counter = 0;

void increment() {
    counter++;  // TSan이 데이터 레이스 탐지
}

int main() {
    thread t1(increment);
    thread t2(increment);
    t1.join();
    t2.join();
}

Valgrind

valgrind --leak-check=full ./program

자주 발생하는 UB

1. 배열 범위 초과

// ❌
int arr[5];
for (int i = 0; i <= 5; i++) {  // <= 주의!
    arr[i] = 0;
}

// ✅
for (int i = 0; i < 5; i++) {
    arr[i] = 0;
}

2. 문자열 종료 누락

// ❌
char str[5] = "hello";  // '\0' 공간 없음 (UB)

// ✅
char str[6] = "hello";  // '\0' 포함

3. 삭제 후 사용

// ❌
int* ptr = new int(10);
delete ptr;
cout << *ptr << endl;  // UB

// ✅
int* ptr = new int(10);
int value = *ptr;
delete ptr;
ptr = nullptr;
cout << value << endl;

4. 타입 펀닝

// ❌ UB (strict aliasing 위반)
int x = 10;
float* f = reinterpret_cast<float*>(&x);
cout << *f << endl;

// ✅ memcpy 사용
int x = 10;
float f;
memcpy(&f, &x, sizeof(int));
cout << f << endl;

5. 순서 미정의

// ❌ UB
int i = 0;
arr[i] = i++;  // i를 읽고 쓰는 순서 미정의

// ✅ 명확한 순서
int i = 0;
arr[i] = i;
i++;

UB 회피 전략

1. 초기화

// 모든 변수 초기화
int x = 0;
int* ptr = nullptr;

// C++11 유니폼 초기화
int x{};  // 0으로 초기화

2. 범위 체크

// at() 사용
vector<int> v(5);
v.at(10);  // 예외 발생

// 범위 기반 for
for (int x : v) {
    // 안전
}

3. 스마트 포인터

// unique_ptr, shared_ptr 사용
auto ptr = make_unique<int>(10);
// 자동 해제

4. const 사용

const int x = 10;
// x = 20;  // 컴파일 에러 (UB 방지)

5. Sanitizer 사용

# 개발 중 항상 사용
g++ -fsanitize=address,undefined -g program.cpp

컴파일러 최적화와 UB

// UB가 있으면 컴파일러가 이상한 최적화
int* ptr = nullptr;

if (ptr != nullptr) {
    *ptr = 10;
}

// 컴파일러: "ptr이 역참조되므로 nullptr일 수 없다"
// if 문 제거! (최적화)

FAQ

Q1: UB는 왜 존재하나요?

A:

  • 성능 최적화 여지
  • 플랫폼 독립성
  • 하드웨어 차이

Q2: UB를 어떻게 피하나요?

A:

  • 변수 초기화
  • 범위 체크
  • Sanitizer 사용
  • 코드 리뷰
  • 정적 분석 도구

Q3: UB가 발생하면?

A:

  • 크래시
  • 잘못된 결과
  • 보안 취약점
  • 예측 불가능한 동작

Q4: 모든 UB를 찾을 수 있나요?

A: 아니요. 하지만 Sanitizer와 정적 분석으로 대부분 찾을 수 있습니다.

Q5: UB와 Implementation-Defined의 차이는?

A:

  • UB: 아무 일이나 일어날 수 있음
  • Implementation-Defined: 컴파일러가 정의하고 문서화

Q6: UB 학습 리소스는?

A:

  • cppreference.com (UB 목록)
  • “Effective C++” (Scott Meyers)
  • Sanitizer 문서

같이 보면 좋은 글 (내부 링크)

이 주제와 연결되는 다른 글입니다.

  • C++ 코드 리뷰 | “체크리스트” 20가지 [실무 필수]
  • C++ 템플릿 특수화 | template specialization 가이드
  • C++ Default Initialization | “기본 초기화” 가이드

관련 글

  • C++ 미정의 동작 (UB) 완벽 가이드 |