Programming Search⌘K

Conceptcore

Pointers and references

Also called pointer, reference, address, indirection, alias.

A reference is a value that leads to another value, so several parts of a program can share one object without copies. A pointer is a reference that holds a memory address.

Applies to
core-languages

Idea

A program often needs to reach one value from several places. It can copy the value into each place. It can also store, in each place, a small value that leads to one shared copy. That small value is a reference. A pointer is a reference that holds the address of the value in memory.4

References serve four common needs:

  • Sharing without copies. A function can read or change a large object, and only a reference moves.
  • Linked data structures. A node of a list, a tree or a graph holds references to other nodes.
  • Out parameters. A function can change a variable of its caller through a reference to that variable.
  • Dynamic allocation. A program makes objects at run time and keeps a reference to each one.

Two names that refer to one object are aliases. A change through one name shows through the other. In Python, every variable holds a reference, so an assignment makes an alias, not a copy.17

scores = [10, 20, 30]
alias = scores
alias.append(40)
print(scores)
print(alias is scores)
Output
[10, 20, 30, 40]
True

How it works

Addresses and indirection

The memory of a machine is a sequence of cells, and each cell has a number, its address. A load instruction reads the value at an address. A store instruction writes a value to an address. A pointer is a variable whose value is an address. To follow the pointer to the value is called indirection, or dereferencing.

In C, the unary operator & gives the address of an object, and the unary operator * gives the object that a pointer points to.5 The diagram shows a variable x and a pointer p to it. The addresses are illustrative.

name   address   contents
x      1000      42
p      1008      1000     p points to x, so *p is 42

A read of *p is two loads: one to get the address in p, one to get the value at that address. A write *p = 7 is a load of p and a store to the address. When p does not hold the address of a valid object, the behaviour of *p is undefined.5

A pointer has a fixed size, whatever the size of the object it points to. That size depends on the machine and the compiler; the C example prints it. Each object type also has an alignment. Its address must be a multiple of a number of bytes that the implementation defines.8

C allows arithmetic on pointers into an array. p + 1 points to the next element, not the next byte. A pointer may also point one past the last element, but a dereference there is undefined.6 The subscript p[i] is defined as *(p + i).7

A pointer is valid only while its object exists. When the lifetime of the object ends, the value of the pointer becomes indeterminate. A use of the object after that point is undefined.9 Such a pointer is a dangling pointer. The C pitfall below shows one.

Value semantics and reference semantics

Under value semantics, an assignment copies the value. The two variables are then independent. Under reference semantics, a variable holds a reference, and an assignment copies the reference. Both variables then refer to one object.

Most languages mix the two:

  • Java. Primitive types such as int hold values. Class, interface and array types hold references, and there can be many references to one object.14
  • C#. A variable of a struct type contains an instance of the type. A variable of a class type contains a reference.33
  • Go. An array is a value, and an assignment copies its elements. A slice refers to an underlying array, so a copy of a slice shares the elements (see the Go example).
  • C and C++. An assignment of a struct or a class object copies it. Sharing needs an explicit pointer or, in C++, a reference.
  • Python, JavaScript, Kotlin. Every object is reached through a reference. Objects that cannot change, such as Python integers, make the difference hard to see.

Reference semantics adds a question that value semantics does not need: are two references the same object, or only equal objects? Each language has a separate test for identity.

Language Identity of objects Equality of contents
Python a is b17 a == b
Java a == b16 a.equals(b)
JavaScript, TypeScript a === b on objects21 written by hand
Kotlin a === b35 a == b
C# ReferenceEquals(a, b) a.Equals(b)
Go, C, C++ p == q on pointers *p == *q
Rust std::ptr::eq(a, b) a == b on references

Pass by value and pass by reference

Under pass by value, the parameter is a fresh variable that gets a copy of the argument. Under pass by reference, the parameter is a second name for the variable of the caller. An assignment to the parameter then changes the variable of the caller.

Many languages pass by value only. C assigns the value of each argument to the parameter.10 Java initializes fresh parameter variables with the argument values.15 Python passes arguments by assignment, so it has no call by reference.18 Go passes everything by value; a map or slice value behaves like a pointer, so the callee can change the shared contents.24

When the argument is a reference, these languages copy the reference. The callee can change the object, because the caller and the callee share it. The callee cannot make the variable of the caller refer to a different object. The examples show both cases with a function rebind, which has no effect, and a function append, whose change the caller sees.

A few languages also have true pass by reference:

  • C++. A parameter of type T& is a reference. Argument passing is initialization, so the parameter becomes an alias for the argument.12
  • C#. A ref parameter is an alias for the variable of the caller. Both the declaration and the call must use the keyword ref.32 Without it, a class parameter gets a copy of the reference, and a struct parameter gets a copy of the value.31
  • PowerShell. A parameter of type [ref] holds a PSReference to the variable of the caller. The function reads and writes the variable through its Value property.36

Rust and C get the same effect with an explicit pointer: the caller writes &mut x or &x, and the callee writes *r = 42.

References in C++

A C++ reference is an alias for an object, not an object of its own. The standard does not say whether a reference needs storage.11 It has three rules that pointers do not have:

  • A reference must be initialized when it is declared. The exceptions are parameters, return types, class members and extern declarations.1112
  • A reference cannot be changed to refer to another object after its initialization. r = b assigns the value of b to the object that r refers to.12
  • A null reference cannot exist in a well-defined program. There are no references to references, no arrays of references and no pointers to references.11

The C++ example shows the second rule: after r = b, the address of r is still the address of a.

Managed references and raw pointers

In Java, Python, JavaScript and Kotlin, and in the safe parts of Go and C#, a reference can only be made from an existing object. The program cannot do arithmetic on it and cannot convert an integer into it. The runtime keeps an object alive while a reference to it exists (Garbage collection). So a managed reference cannot dangle. Go has pointers but no pointer arithmetic. The Go FAQ gives safety as the reason. It adds that a loop with array indices can be as efficient, and that the absence of pointer arithmetic helps the implementation of the garbage collector.25 When the address of a local variable leaves the function, the Go compiler puts the variable on the heap, so the pointer stays valid.26

C and C++ have raw pointers with arithmetic and casts. The compiler does not track lifetimes, so a dangling pointer is possible. C# has pointer types too, but only inside an unsafe context, and the project must allow unsafe blocks.34

Borrows in Rust

Rust has two kinds of reference. A shared reference &T allows reading, and any number of them may exist at one time. A mutable reference &mut T is the only way to reach its value while it exists.27 The borrow checker enforces the rule at compile time: either one mutable reference or any number of shared references. References must always be valid, so a reference cannot outlive its value.29

Rust also has raw pointers *const T and *mut T, with no guarantees of safety or liveness.27 To dereference a raw pointer is an unsafe operation, so it must be inside an unsafe block.28

In languages

LanguageVerdictNote
PythonNative
C++Native
JavaNative
CNative
C#Native
JavaScriptNative
TypeScriptNative
GoNative
RustNative
KotlinNative
SQLDoes not applyA query works on values in rows, with no addresses. A row refers to another row by the value of a key, which is a foreign key, not a pointer.
BashIdiomBash has no references to values. A function gets the name of a variable and assigns to it with printf -v or through a nameref made by declare -n or local -n. The node shows the printf -v form in a run block. Alternative: A global variable, or output on stdout that the caller captures with command substitution.
PowerShellNative
HTMLDoes not applyMarkup has no variables in memory. An id and a link that names it refer to an element by name.
CSSDoes not applyStyle rules have no variables in memory.
Regular expressionsDoes not applyA pattern has no variables in memory. A backreference refers to captured text, not to a value in memory.

The example files show the same small program in each language: a function that tries to change its argument, and two names for one object.

Language Verdict Form
Python native every variable holds a reference; is compares identity
JavaScript native objects are reached through references; === compares identity
TypeScript native as JavaScript
Java native reference types; == on references compares identity
C native pointer types T *, operators & and *, pointer arithmetic
C++ native pointers T* and references T&
C# native class types, ref parameters, pointers in unsafe code
Go native pointer types *T; no pointer arithmetic
Rust native references &T and &mut T checked by the borrow checker; raw pointers
Kotlin native references to objects; === compares identity
PowerShell native references to .NET objects; [ref] parameters
Bash idiom the name of a variable, used through printf -v or a nameref
SQL n/a a row refers to another row by the value of a key
Regex n/a a pattern has no variables in memory
HTML n/a markup has no variables in memory
CSS n/a style rules have no variables in memory

Bash has strings and arrays, but no reference to a value. The idiom passes the name of a variable instead. The builtin printf -v name assigns its output to the variable called name.38 The nameref attribute, set with declare -n or local -n, makes a variable that refers to another variable by name.37

set_to_42() {
  printf -v "$1" '%s' 42
}

count=1
set_to_42 count
echo "after set_to_42: $count"
Output
after set_to_42: 42
PythonGitHub
def rebind(items):
    items = [0, 0, 0]


def append(items):
    items.append(4)


numbers = [1, 2, 3]
rebind(numbers)
print("after rebind:", numbers)
append(numbers)
print("after append:", numbers)

alias = numbers
alias[0] = 100
print("numbers:", numbers)
print("alias is numbers:", alias is numbers)

copy = list(numbers)
print("copy is numbers:", copy is numbers)
print("copy == numbers:", copy == numbers)
Output
after rebind: [1, 2, 3]
after append: [1, 2, 3, 4]
numbers: [100, 2, 3, 4]
alias is numbers: True
copy is numbers: False
copy == numbers: True
  • Verdict: native. Every Python variable holds a reference to an object. The language has no pointer type and no address operator.
  • Arguments are passed by assignment. The parameter items is a second name for the list of the caller. An assignment to items changes only the parameter, so rebind has no effect.
  • A method call on the parameter, such as append, changes the shared list, and the caller sees the change.
  • alias = numbers copies the reference, not the list. is compares identity, and == compares values.
  • Python has no call by reference. A function that must give back several values returns a tuple, and the caller assigns the parts.
#include <print>
#include <vector>

void set_copy(int n) {
    n = 42;
    std::println("inside set_copy: {}", n);
}

void set_pointer(int* p) { *p = 42; }

void set_reference(int& r) { r = 42; }

int main() {
    int x = 1;
    set_copy(x);
    std::println("after set_copy: {}", x);
    set_pointer(&x);
    std::println("after set_pointer: {}", x);
    x = 1;
    set_reference(x);
    std::println("after set_reference: {}", x);

    int a = 1;
    int b = 2;
    int& r = a;
    r = b;
    std::println("a: {}, &r == &a: {}", a, &r == &a);

    std::vector<int> numbers{1, 2, 3};
    std::vector<int> copy = numbers;
    std::vector<int>& alias = numbers;
    alias[0] = 100;
    std::println("numbers[0]: {}, copy[0]: {}", numbers[0], copy[0]);
}
Output
inside set_copy: 42
after set_copy: 1
after set_pointer: 42
after set_reference: 42
a: 2, &r == &a: true
numbers[0]: 100, copy[0]: 1
  • Verdict: native. C++ has pointers (T*), which come from C, and references (T&).
  • A reference is an alias for an object. It must be initialized, and it cannot be changed to refer to another object. So r = b copies the value of b into a.
  • A parameter of type int& is true pass by reference. The call set_reference(x) looks the same as a call by value.
  • Class types have value semantics by default. copy = numbers copies all elements, and only alias shares the vector.
JavaGitHub
import java.util.ArrayList;
import java.util.List;

public class Main {
    static void rebind(List<Integer> items) {
        items = new ArrayList<>(List.of(0, 0, 0));
    }

    static void append(List<Integer> items) {
        items.add(4);
    }

    public static void main(String[] args) {
        List<Integer> numbers = new ArrayList<>(List.of(1, 2, 3));
        rebind(numbers);
        System.out.println("after rebind: " + numbers);
        append(numbers);
        System.out.println("after append: " + numbers);

        List<Integer> alias = numbers;
        alias.set(0, 100);
        System.out.println("numbers: " + numbers);
        System.out.println("alias == numbers: " + (alias == numbers));

        List<Integer> copy = new ArrayList<>(numbers);
        System.out.println("copy == numbers: " + (copy == numbers));
        System.out.println("copy.equals(numbers): " + copy.equals(numbers));
    }
}
Output
after rebind: [1, 2, 3]
after append: [1, 2, 3, 4]
numbers: [100, 2, 3, 4]
alias == numbers: true
copy == numbers: false
copy.equals(numbers): true
  • Verdict: native. A variable of a class, interface or array type holds a reference to an object, or the null reference. Primitive types such as int hold the value itself.
  • A call initializes each parameter with the value of the argument. For an object, this value is the reference, so rebind changes only its own parameter.
  • == on two references is true when they refer to the same object. equals compares the contents.
  • Java has no pointer arithmetic, no address operator and no call by reference.
#include <stdio.h>

static void set_copy(int n) {
    n = 42;
    printf("inside set_copy: %d\n", n);
}

static void set_pointer(int *p) { *p = 42; }

static void swap(int *a, int *b) {
    int t = *a;
    *a = *b;
    *b = t;
}

int main(void) {
    int x = 1;
    set_copy(x);
    printf("after set_copy: %d\n", x);
    set_pointer(&x);
    printf("after set_pointer: %d\n", x);

    int a = 1;
    int b = 2;
    swap(&a, &b);
    printf("after swap: a=%d b=%d\n", a, b);

    int values[3] = {10, 20, 30};
    int *p = values;
    printf("p[1] == *(p + 1): %d\n", p[1] == *(p + 1));
    printf("p + 3 == &values[3]: %d\n", p + 3 == &values[3]);
    printf("sizeof(int *): %zu, alignof(int): %zu\n", sizeof(int *), alignof(int));
    return 0;
}
Output
inside set_copy: 42
after set_copy: 1
after set_pointer: 42
after swap: a=2 b=1
p[1] == *(p + 1): 1
p + 3 == &values[3]: 1
sizeof(int *): 8, alignof(int): 4
  • Verdict: native. A pointer type T * holds the address of an object of type T. The operator & gives the address, and * reads or writes the object.
  • C passes every argument by value. A function changes a variable of the caller only through a pointer, as in set_pointer and swap.
  • p[i] is defined as *(p + i). Pointer arithmetic moves by whole elements, and a pointer may point one past the last element.
  • The size of a pointer and the alignment of a type depend on the implementation.
var numbers = new List<int> { 1, 2, 3 };
Rebind(numbers);
Console.WriteLine($"after Rebind: {string.Join(", ", numbers)}");
Append(numbers);
Console.WriteLine($"after Append: {string.Join(", ", numbers)}");
RebindRef(ref numbers);
Console.WriteLine($"after RebindRef: {string.Join(", ", numbers)}");

var alias = numbers;
alias[0] = 100;
Console.WriteLine($"numbers[0]: {numbers[0]}");
Console.WriteLine($"same object: {ReferenceEquals(alias, numbers)}");

var point = new Point { X = 1 };
var pointCopy = point;
pointCopy.X = 100;
Console.WriteLine($"point.X: {point.X}");

static void Rebind(List<int> items) => items = new List<int> { 0, 0, 0 };
static void Append(List<int> items) => items.Add(4);
static void RebindRef(ref List<int> items) => items = new List<int> { 0, 0, 0 };

struct Point
{
    public int X;
}
Output
after Rebind: 1, 2, 3
after Append: 1, 2, 3, 4
after RebindRef: 0, 0, 0
numbers[0]: 100
same object: True
point.X: 1
  • Verdict: native. A variable of a class type holds a reference. A variable of a struct type holds the value, so pointCopy is a separate copy.
  • By default, a parameter receives a copy of the argument. For a class, that copy is the reference, so Rebind changes only its parameter.
  • A ref parameter is an alias for the variable of the caller. Both the method and the call must say ref, and RebindRef replaces the list of the caller.
  • ReferenceEquals compares identity. C# also has pointer types, but only in code marked unsafe and compiled with unsafe blocks allowed.
JavaScriptGitHub
function rebind(items) {
  items = [0, 0, 0];
}

function append(items) {
  items.push(4);
}

const numbers = [1, 2, 3];
rebind(numbers);
console.log("after rebind:", numbers.join(", "));
append(numbers);
console.log("after append:", numbers.join(", "));

const alias = numbers;
alias[0] = 100;
console.log("numbers:", numbers.join(", "));
console.log("alias === numbers:", alias === numbers);

const copy = [...numbers];
console.log("copy === numbers:", copy === numbers);
console.log("same elements:", copy.every((x, i) => x === numbers[i]));
Output
after rebind: 1, 2, 3
after append: 1, 2, 3, 4
numbers: 100, 2, 3, 4
alias === numbers: true
copy === numbers: false
same elements: true
  • Verdict: native. A variable holds a primitive value or a reference to an object. Arrays and functions are objects.
  • A call copies the value of each argument into the parameter. For an object, the copied value is the reference. An assignment to the parameter does not reach the caller, and a change to the object does.
  • === compares two objects by identity. Two distinct arrays with the same elements are not equal.
  • The spread [...numbers] makes a shallow copy. The copy holds the same element values, and nested objects stay shared (see Pitfalls).
  • JavaScript has no pointer type and no call by reference.
TypeScriptGitHub
function rebind(items: number[]): void {
  items = [0, 0, 0];
}

function append(items: number[]): void {
  items.push(4);
}

const numbers: number[] = [1, 2, 3];
rebind(numbers);
console.log("after rebind:", numbers.join(", "));
append(numbers);
console.log("after append:", numbers.join(", "));

const alias: number[] = numbers;
alias[0] = 100;
console.log("numbers:", numbers.join(", "));
console.log("alias === numbers:", alias === numbers);

const copy: number[] = [...numbers];
console.log("copy === numbers:", copy === numbers);
Output
after rebind: 1, 2, 3
after append: 1, 2, 3, 4
numbers: 100, 2, 3, 4
alias === numbers: true
copy === numbers: false
  • Verdict: native. TypeScript has the run-time model of JavaScript. A variable of an object type holds a reference.
  • The types are removed before the program runs. They do not change how arguments are passed or how === compares objects.
  • const stops a second assignment to the variable numbers. It does not stop changes to the array, so alias[0] = 100 is valid.
  • TypeScript has no pointer type and no call by reference.
package main

import "fmt"

func setCopy(n int) {
	n = 42
	fmt.Println("inside setCopy:", n)
}

func setPointer(p *int) {
	*p = 42
}

func main() {
	x := 1
	setCopy(x)
	fmt.Println("after setCopy:", x)
	setPointer(&x)
	fmt.Println("after setPointer:", x)

	p := &x
	q := &x
	fmt.Println("p == q:", p == q, "*p:", *p)

	array := [3]int{1, 2, 3}
	arrayCopy := array
	arrayCopy[0] = 100
	fmt.Println("array:", array)

	slice := []int{1, 2, 3}
	sliceAlias := slice
	sliceAlias[0] = 100
	fmt.Println("slice:", slice)
}
Output
inside setCopy: 42
after setCopy: 1
after setPointer: 42
p == q: true *p: 42
array: [1 2 3]
slice: [100 2 3]
  • Verdict: native. The type *T holds a pointer to a variable of type T. The operator & takes the address, and * reads or writes through the pointer.
  • Every argument is passed by value. A function changes a variable of the caller only through a pointer.
  • An array is a value, so the assignment copies all elements. A slice value refers to an underlying array, so the copy shares the elements.
  • Go has no pointer arithmetic. p == q is true here because both pointers point to x.
RustGitHub
fn set_copy(mut n: i32) {
    n = 42;
    println!("inside set_copy: {n}");
}

fn set_through(r: &mut i32) {
    *r = 42;
}

fn main() {
    let mut x = 1;
    set_copy(x);
    println!("after set_copy: {x}");
    set_through(&mut x);
    println!("after set_through: {x}");

    let numbers = vec![1, 2, 3];
    let a = &numbers;
    let b = &numbers;
    println!("a and b are the same vector: {}", std::ptr::eq(a, b));
    let copy = numbers.clone();
    println!("copy is the same vector: {}", std::ptr::eq(&copy, &numbers));
    println!("copy == numbers: {}", copy == numbers);

    let p = &raw mut x;
    unsafe {
        *p += 1;
    }
    println!("after raw pointer write: {x}");
}
Output
inside set_copy: 42
after set_copy: 1
after set_through: 42
a and b are the same vector: true
copy is the same vector: false
copy == numbers: true
after raw pointer write: 43
  • Verdict: native. A shared reference &T and a mutable reference &mut T point to a value that the compiler proves is alive.
  • The borrow checker allows any number of shared references or one mutable reference at a time. A shared reference stops changes to the value.
  • std::ptr::eq compares two references by address. == on references compares the values.
  • The raw pointers *const T and *mut T have no such guarantees. A dereference of a raw pointer is valid only inside an unsafe block.
  • &raw mut x makes a raw pointer directly, with no reference in between.
KotlinGitHub
class Box(var value: Int)

fun change(box: Box) {
    box.value = 42
}

fun main() {
    val box = Box(1)
    change(box)
    println("after change: ${box.value}")

    val alias = box
    alias.value = 100
    println("box.value: ${box.value}")
    println("alias === box: ${alias === box}")

    val numbers = mutableListOf(1, 2, 3)
    val copy = numbers.toMutableList()
    copy[0] = 100
    println("numbers: $numbers")
    println("copy === numbers: ${copy === numbers}")
    println("copy == listOf(100, 2, 3): ${copy == listOf(100, 2, 3)}")
}
Output
after change: 42
box.value: 100
alias === box: true
numbers: [1, 2, 3]
copy === numbers: false
copy == listOf(100, 2, 3): true
  • Verdict: native. A variable of a class type holds a reference to an object.
  • A call passes the reference. change sets a property of the shared object, and the caller sees it.
  • === is referential equality: both sides point to the same object. == is structural equality and calls equals.
  • val stops a second assignment to the variable. It does not make the object immutable, so alias.value = 100 is valid.
  • Kotlin has no pointer types and no call by reference.
PowerShellGitHub
function Set-Copy($n) {
    $n = 42
    "inside Set-Copy: $n"
}

function Set-Reference([ref]$n) {
    $n.Value = 42
}

$x = 1
Set-Copy $x
"after Set-Copy: $x"
Set-Reference ([ref]$x)
"after Set-Reference: $x"

$table = @{ count = 1 }
$alias = $table
$alias.count = 100
"table.count: $($table.count)"
"same object: $([object]::ReferenceEquals($table, $alias))"
Output
inside Set-Copy: 42
after Set-Copy: 1
after Set-Reference: 42
table.count: 100
same object: True
  • Verdict: native. A variable holds a .NET value or a reference to a .NET object. A hashtable is an object, so $alias and $table share it.
  • A parameter receives a copy of the argument. An integer is a value type, so Set-Copy changes only its own copy.
  • [ref] is the type accelerator for System.Management.Automation.PSReference. The function reads and writes the variable of the caller through the Value property.
  • The call must wrap the variable in [ref] and parentheses, as in Set-Reference ([ref]$x).
  • Null. Many languages let a reference refer to nothing. Java has a special null reference that refers to no object.14 Null reference covers the errors that this causes and the types that exclude it.
  • Smart pointers. A smart pointer is a type that acts as a pointer and also decides when to free the object. The Rust standard library has smart pointer types beyond references and raw pointers.27 Reference counting is one way to decide when to free the object (Garbage collection).
  • Immutable objects. Aliasing causes no surprise when no one can change the shared object. Shared references to immutable values are as safe as copies (Immutability).
  • Capture by reference. A closure that captures a variable keeps a reference to it (Closure). The same rules of lifetime apply.
  • Recursive data. A list or a tree is a node with references to smaller nodes, and a recursive function walks it (Recursion).
  • Indices as references. An index into an array also leads to a value. BCPL and B treated a pointer as an integer index into the array of memory cells.2

Pitfalls

Repetition copies references, not objects

In Python, s * n does not copy the items of s. It refers to them n times.20 So [[0] * 3] * 3 is a list of three references to one inner list.19

This code runs but gives a wrong answer on purpose.

grid = [[0] * 3] * 3
grid[0][0] = 1
print(grid)
Output
[[1, 0, 0], [1, 0, 0], [1, 0, 0]]

The fix makes a separate inner list for each row: [[0] * 3 for _ in range(3)]. The inner [0] * 3 is safe, because integers cannot change.

A swap of two references does not swap

A Java method gets copies of the references of its caller.15 A swap of the parameters exchanges only the copies.

This code runs but gives a wrong answer on purpose.

public class Main {
    static void swap(StringBuilder a, StringBuilder b) {
        StringBuilder t = a;
        a = b;
        b = t;
    }

    public static void main(String[] args) {
        StringBuilder first = new StringBuilder("first");
        StringBuilder second = new StringBuilder("second");
        swap(first, second);
        System.out.println(first + " " + second);
    }
}
Output
first second

The variables first and second still refer to the same objects. A method can swap two elements of an array or a list, because it changes the shared container. Python, JavaScript, Go and Kotlin behave in the same way. C++ and C# can swap with reference parameters, and C can swap with pointers (see the C example).

A pointer to a local outlives the local

A local variable of a C function lives until the function returns. A pointer to it is then dangling, and a read through it is undefined.9

This code has a memory error, on purpose, and the sanitizer reports it.

#include <stdio.h>

int *make_value(void) {
    int value = 42;
    return &value;
}

int main(void) {
    int *p = make_value();
    printf("%d\n", *p);
    return 0;
}

The compiler warns address of stack memory associated with local variable 'value' returned, and AddressSanitizer reports stack-use-after-return. In a build without the sanitizer, the program printed 42 and exited with status 0, which hides the bug. The fix returns the value itself, or memory from malloc that the caller frees.

A reference into a vector dangles after growth

When a std::vector grows past its capacity, it moves its elements to a larger buffer. Then all references, pointers and iterators to the elements are invalid.13

This code has a memory error, on purpose, and the sanitizer reports it.

#include <print>
#include <vector>

int main() {
    std::vector<int> scores = {10, 20, 30};
    int& first = scores[0];
    scores.push_back(40);
    first += 1;
    std::println("{}", scores[0]);
}

AddressSanitizer reports heap-use-after-free at the line first += 1. In a build without the sanitizer, the program printed 10, so the increment went to freed memory. The fix uses an index after the growth, as in scores[0] += 1.

Rust rejects the same program

The Rust version of the vector pitfall does not compile. push needs a mutable borrow of scores, while the shared borrow first is still in use.29

This code does not compile, on purpose.

fn main() {
    let mut scores = vec![10, 20, 30];
    let first = &scores[0];
    scores.push(40);
    println!("{first}");
}

The compiler stops with error E0502, "cannot borrow scores as mutable because it is also borrowed as immutable".30 The fix ends the use of first before the push, or copies the value with let first = scores[0];.

A shallow copy shares nested objects

In JavaScript, the spread syntax copies the properties of an object. A property that holds an object is copied as a reference, so the copy and the original share it.

This code runs but gives a wrong answer on purpose.

const defaults = { name: "report", tags: [] };
const report = { ...defaults };
report.tags.push("draft");
console.log(defaults.tags);
Output
[ 'draft' ]

The fix copies the nested array too, as in { ...defaults, tags: [...defaults.tags] }.

Cost

  • Indirection. A read through a pointer needs the address before the value, so it costs at least one extra load. A chain of pointers costs one load for each step.
  • Storage. Each reference costs one pointer of storage, and the C example prints that size.
  • Copy against share. To pass a reference costs the same for any size of object. To pass a value costs a copy of the whole value, but the callee then reads it with no indirection.
  • Locality. The nodes of a linked structure can lie anywhere in memory. The elements of an array lie next to each other, so a walk over an array touches fewer cache lines than a walk over a linked list.
  • Heap allocation. A value that a reference must keep alive often lives on the heap. In Go, the compiler moves a variable to the heap when its address escapes the function.26 Managed heaps add the cost of Garbage collection.

History

  • 1964 and 1965. Harold Lawson invented the pointer variable at IBM and put it into PL/I. It gave a general-purpose high-level language a flexible way to handle linked lists.1
  • Mid-1960s. Martin Richards designed BCPL. In BCPL, memory is an array of cells, and a pointer is an integer index into it. The indirection operator was rv, later !. B used the unary *.2
  • 1967. Lawson described the pointer variable in "PL/I List Processing", in the June issue of Communications of the ACM.1
  • 1969 to 1973. Dennis Ritchie and others built C. Pointers in C hold byte addresses, so a dereference needs no scaling. Pointer arithmetic scales the integer by the size of the object instead.2
  • C++. Bjarne Stroustrup kept the pointers of C for compatibility. He added references directly to support operator overloading. He compares the design with Simula, which has separate operators for assignment to the object and to the reference.3

References

  1. IEEE Computer Society, Harold W. (Bud) Lawson, 2000 Computer Pioneer Award, the award citation and the biography (the pointer variable, PL/I, 1964-65, "PL/I List Processing" in CACM, June 1967)
  2. Dennis M. Ritchie, The Development of the C Language, HOPL-II, 1993, sections Origins, the languages; Problems of B; Embryonic C
  3. Bjarne Stroustrup, C++ Style and Technique FAQ, Why does C++ have both pointers and references?
  4. ISO/IEC 9899:201x, Programming languages, C (N1570, the C11 draft), 6.2.5 Types, paragraph 20 (pointer types)
  5. ISO/IEC 9899:201x, Programming languages, C (N1570, the C11 draft), 6.5.3.2 Address and indirection operators, paragraphs 3 and 4
  6. ISO/IEC 9899:201x, Programming languages, C (N1570, the C11 draft), 6.5.6 Additive operators, paragraph 8
  7. ISO/IEC 9899:201x, Programming languages, C (N1570, the C11 draft), 6.5.2.1 Array subscripting, paragraph 2
  8. ISO/IEC 9899:201x, Programming languages, C (N1570, the C11 draft), 6.2.8 Alignment of objects, paragraph 1
  9. ISO/IEC 9899:201x, Programming languages, C (N1570, the C11 draft), 6.2.4 Storage durations of objects, paragraph 2
  10. ISO/IEC 9899:201x, Programming languages, C (N1570, the C11 draft), 6.5.2.2 Function calls, paragraph 4
  11. Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [dcl.ref], paragraphs 4 and 5
  12. Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [dcl.init.ref], paragraphs 1 and 2
  13. Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [vector.modifiers], paragraph 2
  14. The Java Language Specification, Java SE 25 Edition, 4.3.1 Objects
  15. The Java Language Specification, Java SE 25 Edition, 8.4.1 Formal Parameters
  16. The Java Language Specification, Java SE 25 Edition, 15.21.3 Reference Equality Operators == and !=
  17. The Python Language Reference, Data model, Python 3.14, 3.1 Objects, values and types
  18. Python Programming FAQ, Python 3.14, How do I write a function with output parameters (call by reference)?
  19. Python Programming FAQ, Python 3.14, How do I create a multidimensional list?
  20. The Python Standard Library, Built-in Types, Python 3.14, Common Sequence Operations, note 2
  21. ECMA-262, ECMAScript 2026 Language Specification, 7.2.11 SameValueNonNumber
  22. The Go Programming Language Specification, Pointer types
  23. The Go Programming Language Specification, Address operators
  24. Go FAQ, When are function parameters passed by value?
  25. Go FAQ, Why is there no pointer arithmetic?
  26. Go FAQ, How do I know whether a variable is allocated on the heap or the stack?
  27. The Rust Reference, Pointer types (rules type.pointer.reference.shared, type.pointer.reference.mut, type.pointer.raw, type.pointer.smart)
  28. The Rust Reference, Unsafety (rule safety.unsafe-deref)
  29. The Rust Programming Language, References and Borrowing, The Rules of References
  30. Rust Compiler Error Index, E0502
  31. C# language reference, Method parameters, Pass by value and pass by reference
  32. C# language reference, Method parameters, ref parameter modifier
  33. C# language reference, Value types, the introduction (a variable of a value type contains an instance of the type)
  34. C# language reference, Unsafe code, pointer types, and function pointers, Pointer types
  35. Kotlin documentation, Equality, Referential equality
  36. PowerShell documentation, about_Ref, Long description; Writing functions to accept reference parameters
  37. Bash Reference Manual, 3.4 Shell Parameters (the nameref attribute)
  38. Bash Reference Manual, 4.2 Bash Builtin Commands, printf

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/VX3T75/text.yaml