5.2 Pointers, References, and Object Identity
To use a value, code needs its address, and a pointer is a variable that holds one. Under copy-on-modify semantics, pointers make object identity, whether two names reach the same object, a different question from value equality.
5.2.1 Pointers and indirection
A pointer is an address. On a 64-bit system, a pointer is an 8-byte integer (0 through 2^64 - 1). It names a byte in memory.
int x = 42;
int* p = &x; // p holds the address of x
*p = 50; // dereference: follow the pointer to xHere, p holds an address. *p means “the value at that address.” Dereferencing requires the address to be valid. If p points to freed memory, dereferencing is undefined.
In C, going through a pointer is a choice. In R it is the only way to reach an object, because a variable binding holds a pointer and never the object itself. That indirection is what lets two names share one object, and an object outlive the code that made it.
In R, every user-visible object is a SEXP. A SEXP is a pointer to a SEXPREC structure on the heap.
x <- c(1, 2, 3) # x holds a SEXP pointer
y <- x # y holds the same pointerBoth x and y point to the same vector on the heap. A change made through one name never shows through the other: copy-on-modify copies the vector before the first write, as shown further down.
A pointer’s validity depends on the memory it points to. When memory is freed, the pointer becomes invalid.
5.2.2 Addresses and virtual memory
Addresses are not physical locations on RAM. The operating system maintains a page table that maps virtual addresses to physical frames.
Two processes can have the same virtual address 0x1234. That address in process-A points to one physical frame. The same address in process-B points to a different frame.
Within one process, virtual addresses are unique. Address 0x1234 always names the same memory.
When a thread is created, it shares the address space (page table) with other threads in the process. All threads see the same virtual addresses. A pointer is valid for all threads in the process.
This is why cross-interpreter sharing is dangerous in the apartment model. Interpreter-1 allocates a SEXP at address 0x5678. Interpreter-2 holds the pointer 0x5678. When interpreter-1 is destroyed, its heap is freed. Address 0x5678 becomes invalid. Interpreter-2’s pointer now points to freed memory.
5.2.3 References and borrowing
In Rust, a reference is temporary access to an object. Unlike a raw pointer, it has a lifetime that the compiler checks.
&x is an immutable reference to x. The reference lasts as long as the code needs it, then it expires.
let x = vec![1, 2, 3];
let r = &x; // immutable reference to x
drop(x); // error[E0505]: cannot move out of `x` because it is borrowed
println!("{}", r[0]); // r is still live here, so the drop above is rejectedRust’s compiler enforces that references never outlive the object they point to. This is the borrow checker. The order in that example matters: move the println! above the drop and the code compiles, because the borrow has ended by then. The checker tracks where a reference is last used, not where its variable goes out of scope.
R has no borrow checker, and R code does not need one: the collector frees only objects that nothing reachable points to, so an R variable never holds a dangling pointer. C code can. A package that keeps a SEXP in a C variable without PROTECT or R_PreserveObject can find the object freed by the next allocation, and reading it then is undefined behavior.
GNU R does not detect this in a normal run. The bug class is common enough that Tomas Kalibera wrote rchk <https://github.com/kalibera/rchk>, a static checker for missing protection. Its README reports a few hundred such bugs found and fixed in R itself, and CRAN runs it on packages with compiled code.
5.2.4 Object identity and values
Here R will mislead you if you trust the name. identical() compares values, not addresses, so it cannot tell you whether two names refer to one object.
x <- c(1, 2, 3)
y <- c(1, 2, 3) # a separate vector with the same contents
z <- x # another name for the same vector
identical(x, y) # TRUE
identical(x, z) # TRUEBoth answers are TRUE, and only one of the two pairs shares an address. To ask the address question you have to leave the ordinary vocabulary and use tracemem(), which returns the object’s address as a string:
tracemem(x) # "<000001D66C587CC8>"
tracemem(z) # "<000001D66C587CC8>" same object
tracemem(y) # "<000001D66C587C78>" different object, equal contentsThe gap follows from copy-on-modify, which hides sharing from ordinary code, so no ordinary function reports it. Environments are the exception, because they have reference semantics and no copy-on-modify, so identical() on two empty environments returns FALSE.
Identity matters for performance. If x and y point to the same object, a read-only operation does not need to copy. If they are separate objects, no operation on x affects y.
5.2.5 Copy-on-modify and identity
When y <- x, the interpreter does not copy. It increments a reference counter and gives both x and y the same SEXP pointer.
x <- c(1, 2, 3) # SEXP A, refcount = 1
y <- x # SEXP A, refcount = 2Now modify y:
y[1] <- 10 # if refcount > 1, copy SEXP A to SEXP BThe interpreter checks the reference count. It is 2. Only y needs 10 at position 1. x needs the original 1. The interpreter creates a copy, modifies the copy, and updates y to point to the new SEXP.
After modification:
x -> SEXP A (1, 2, 3), refcount = 1
y -> SEXP B (10, 2, 3), refcount = 1They are now separate objects. identical(x, y) is FALSE.
Copy-on-modify makes the second object without any sign that it did. A function that modifies its argument modifies a private copy, and the caller’s object stays unchanged.
Identity changes every time copy-on-modify makes a copy. Two list elements that share one vector become two separate vectors as soon as either is modified.
5.2.6 Pointers in multithreaded code
In a multithreaded program, a pointer is only as valid as the memory it points to. If one thread frees memory, pointers from other threads become invalid.
This is why the apartment model forbids sharing SEXPs. Interpreter-1 allocates a SEXP. Interpreter-2 receives the pointer. When interpreter-1’s garbage collector runs, it does not see interpreter-2’s reference, so it can free the SEXP. Interpreter-2’s pointer is now invalid.
A lock around the pointer does not help, because the collector that frees the object never takes that lock. Once the memory is freed, the pointer is useless.
A pointer is valid only while its memory is alive. Once thread A frees the object, thread B’s copy of the pointer dangles, and no lock around the pointer brings the memory back.
5.2.7 Avoiding pointer invalidation
The apartment model solves this by forbidding sharing. Interpreter-1’s SEXP pointers are never given to interpreter-2. Each interpreter holds its own objects.
Communicating across interpreters requires copying or serialization.
Alternative approaches:
Reference counting across interpreters. Instead of plain reference counts, use atomic operations to count references across interpreters. When the count reaches zero, the object is freed. Cost: contention and complexity.
Shared immutable data. If an object never changes, both interpreters can hold the same pointer. The garbage collector must not free it while the other interpreter references it. Cost: mark shared objects specially, prevent collection of shared objects.
Epoch-based reclamation. Each thread announces when it starts and stops using shared pointers. An object that is unlinked while some thread might still hold a pointer to it is freed only after every thread has moved past that point. Rust’s crossbeam-epoch crate implements this. Cost: one stalled thread holds back all reclamation.
The apartment model (isolation with copying) is simpler than any mechanism for controlled pointer sharing across interpreters.
Further reading
- Kernighan and Ritchie, “The C Programming Language”, 2nd edition (Prentice Hall, 1988), chapter 5, “Pointers and Arrays”
- Rust Book, chapter 4, “Understanding Ownership”: https://doc.rust-lang.org/book/ch04-00-understanding-ownership.html
- “Writing R Extensions”, section 5.9.1, “Handling the effects of garbage collection”: https://cran.r-project.org/doc/manuals/r-release/R-exts.html#Garbage-Collection
- Ulrich Drepper, “What Every Programmer Should Know About Memory” (2007), on caches and address translation: https://www.akkadia.org/drepper/cpumemory.pdf
Where this appears
- threaded-r Apartment model forbids sharing SEXPs across interpreters because pointers become invalid. Understanding indirection is essential.
- r-in-rust (rrs) Rust’s ownership model encodes pointer safety into types. Enforcing isolation requires understanding what a pointer means.