Pointers and Memory

const Correctness

const lets an API promise which objects it will not modify and allows the compiler to reject accidental writes.

What is const Correctness?

const lets an API promise which objects it will not modify and allows the compiler to reject accidental writes.

Express read-only data and mutable pointers precisely.

Important points

  • Every pointer must refer to a live compatible object or be null.
  • Pair each owned allocation with exactly one release.
  • Prefer clear ownership and const-correct interfaces.

C and C++ code examples

C
Run code →
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;
}
Expected output
12
C++
Run code →
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';
}
Expected output
12

C and C++ comparison

Read declarations from the variable outward: pointer-to-const protects the pointed value, while a const pointer prevents reseating. C++ also supports const member functions.

C

Ownership and cleanup are conventions enforced by the programmer.

C++

Containers and RAII types can encode ownership and cleanup in object lifetimes.

Practice exercises

Run both versions, then modify them to observe the different language guarantees.

  • Test null and allocation-failure paths.
  • Run with AddressSanitizer and UndefinedBehaviorSanitizer.
  • Document whether every pointer owns or only observes its object.