본문 바로가기

C++

Segmentation fault 상황 사례

[1. 개요]

아래 세그멘테이션 폴트 사례는 오염 된 포인터 변수에 접근 시 발생함.

엄밀하게 말하면 스택 오버플로우가 아니기 때문임.


[2. 예제]

#include <iostream>

#define MAX_LEN 5

struct A {
    int arr[MAX_LEN];
    int len;
};

class MyContainer {
private:
    // 메모리 배치를 고려하면...
    A first;

    const int *bptr;
    const char *cptr;
    const float *dptr;

public:
    MyContainer() {
        first.len = 0;

        bptr = new int[MAX_LEN];
        cptr = new char[MAX_LEN];
        dptr = new float[MAX_LEN];
    }

    void push() {
        first.arr[first.len] = first.len;
        first.len += 1;
    }

    friend std::ostream& operator<<(std::ostream& os, MyContainer &con) {
        os << std::hex << (void*)con.bptr << std::endl;
        os << std::hex << (void*)con.cptr << std::endl;
        os << std::hex << (void*)con.dptr << std::endl;

        return os;
    }
};

int main()
{
    MyContainer container;

    std::cout << container << std::endl;

    container.push();
    container.push();
    container.push();
    container.push();
    container.push();
    container.push();
    container.push();

    std::cout << container << std::endl;

    container.push();
    container.push();

    std::cout << container << std::endl;

    return 0;
}

 

위 상황이 정말 위험한 이유는, 디버깅을 더 어렵게 하기 때문임.


[3. 해결 책?]

class MyContainer {
private:
    // 메모리 배치를 고려하면...
    A * first;

    const int *bptr;
    const char *cptr;
    const float *dptr;

public:
    MyContainer() {
        first = new A;

        bptr = new int[MAX_LEN];
        cptr = new char[MAX_LEN];
        dptr = new float[MAX_LEN];
    }
    
    ....
};

 

전부 힙에 할당하고, 리눅스 기준 할당 된 힙 메모리 범위를 벗어나면 즉시 fault 상황을 유도 할 수 있음.(?)

'C++' 카테고리의 다른 글

STL priority_queue  (0) 2021.10.28
가변인자 템플릿  (0) 2021.10.27
std::filesystem  (0) 2021.10.27
std::shared_ptr  (0) 2021.10.27
std::unique_ptr  (0) 2021.10.27