1 minute read

Abstract

이 게시글은 모호한 포인터 사용을 제거해 메모리를 비롯한 자원을 안정적으로 사용할 수 있는 기법들에 대해 설명한다.

0. Overview

이 게시글의 구성은 아래와 같다.

  1. The problem: Resource leaks and memory corruption
  2. Constraints on any solution: Generality, performance, and compatibility
  3. Memory safety: Eliminate dangling pointers and access to deleted objects
  4. Resource safety: Eliminate resource leaks
  5. Other problems: Concurrency, casts, range errors, etc.
  6. Historical note: Where did the solutions come from?

1. Introduction

아래 코드를 보자.

void use(FILE* p);

int some_code(int x)
{
    FILE* f = fopen("foo", "w");
    if (f==0) error("cannot open file");
    if (0<x) {
        use(f);
        // ... do a lot of work ...
    }
    else
        return -1;
    long pos = ftell(f);            // read through f
    // ...
    fprintf(f, "Die, die, die!\n"); // read and write through f
    fclose(f);
    return 0;

이 코드는 마치 아무런 문제가 없는 듯 하다. 그러나 함수 use()가 아래와 같다면 얘기는 달라진다.

void use(FILE* p)
{
    // ...
    free(p);
    // ...
}

숙련된 C/C++ 개발자라면 이 간단한 예제의 문제점들을 빠르게 해결할 수 있을 것이다.

References


Leave a comment