포인터와 메모리

const correctness

const는 변경하지 않을 계약을 나타내고 잘못된 write를 compiler가 거부합니다.

const correctness이란?

const는 변경하지 않을 계약을 나타내고 잘못된 write를 compiler가 거부합니다.

읽기 전용 데이터와 변경 가능한 pointer를 정확히 표현합니다.

중요한 점

  • 포인터는 살아 있는 호환 객체를 가리키거나 null이어야 합니다.
  • 소유한 allocation은 정확히 한 번 해제하세요.
  • Ownership과 const를 명확히 표현하세요.

C와 C++ 코드 예제

C
실행 →
main.c
#include <stdio.h>

int sum(const int *values, size_t count) {
    int total = 0;
    for (size_t i = 0; i < count; ++i) total += values[i];
    return total;
}

int main(void) {
    const int values[] = {2, 4, 6};
    printf("%d\n", sum(values, 3));
    return 0;
}
예상 출력
12
C++
실행 →
main.cpp
#include <array>
#include <iostream>

int sum(const std::array<int, 3>& values) {
    int total = 0;
    for (int value : values) total += value;
    return total;
}

int main() {
    const std::array values{2, 4, 6};
    std::cout << sum(values) << '\n';
}
예상 출력
12

C와 C++ 비교

Pointer-to-const는 값을, const pointer는 주소를 고정합니다. C++에는 const member function도 있습니다.

C

Ownership과 cleanup은 개발자가 지켜야 하는 규칙입니다.

C++

Container와 RAII가 ownership과 cleanup을 lifetime에 연결합니다.

연습 문제

두 버전을 실행하고 수정하여 각 언어의 보장을 관찰하세요.

  • null과 할당 실패를 테스트하세요.
  • AddressSanitizer와 UndefinedBehaviorSanitizer를 실행하세요.
  • 각 pointer의 ownership을 문서화하세요.