Programming Search⌘K

Conceptcore

Memory address

Also called memory address, address, addresses, byte address, virtual address, physical address, address space, alignment, offset, address arithmetic.

A memory address is the number of a byte in memory. A value that takes several bytes lives at the address of its first byte, and pointers and references are addresses with rules on top.

Applies to
core-languages

Idea

Memory is a long row of bytes, and each byte has a number, its address. To read or write a value, the processor needs its address. A value that takes several bytes, such as a 4-byte integer, lives at the address of its first byte, so the items of an array are a fixed number of bytes apart, and the fields of a structure are at fixed offsets from its start. Every variable, object and function in a running program is at some address, and a pointer or a reference is, at the bottom, an address that the language lets the program use.

import ctypes

Int32x4 = ctypes.c_int32 * 4
a = Int32x4(10, 20, 30, 40)
base = ctypes.addressof(a)  # a number, different on each run
size = ctypes.sizeof(ctypes.c_int32)
for i in range(4):
    addr = base + i * size  # element i is i * 4 bytes after the start
    print(f"a[{i}] at base + {addr - base}: {ctypes.c_int32.from_address(addr).value}")

raw = bytes((ctypes.c_ubyte * 8).from_address(base))
print("first 8 bytes:", raw.hex(" "))  # little-endian: low byte first

ctypes.c_int32.from_address(base + 2 * size).value = 99  # write through an address
print("after a write at base + 8:", list(a))


class Record(ctypes.Structure):
    _fields_ = [("flag", ctypes.c_char), ("count", ctypes.c_int32), ("tag", ctypes.c_char)]


for name, _ in Record._fields_:
    print(f"Record.{name} at offset {getattr(Record, name).offset}")
print("sizeof(Record):", ctypes.sizeof(Record), "alignment:", ctypes.alignment(Record))
Output
a[0] at base + 0: 10
a[1] at base + 4: 20
a[2] at base + 8: 30
a[3] at base + 12: 40
first 8 bytes: 0a 00 00 00 14 00 00 00
after a write at base + 8: [10, 20, 99, 40]
Record.flag at offset 0
Record.count at offset 4
Record.tag at offset 8
sizeof(Record): 12 alignment: 4

Python hides addresses, but ctypes makes C data and exposes them. The program makes an array of four 32-bit integers and prints each address as an offset from the start, because the address itself is different on each run. Element i is at the start plus 4 * i. The raw bytes show the order inside each integer: 10 is 0a 00 00 00, low byte first, because the machine is little-endian. Writing at the start plus 8 changes a[2]. The structure has a 1-byte field, a 4-byte field and a 1-byte field, but the 4-byte field starts at offset 4 and the whole record takes 12 bytes, because the compiler aligns each field to a multiple of its size.

How it works

Addresses and sizes. On most machines today the unit of addressing is the byte, and an address is an unsigned integer of 64 bits, of which 48 to 57 are in use on x86-64 and ARM64. A value of type T at address a takes the bytes from a to a + size(T) - 1. Element i of an array that starts at a is at a + i * size(T), which is why indexing an array takes constant time. The byte order inside a value, little-endian or big-endian, belongs to the machine: x86 and almost all ARM systems are little-endian.

Alignment and offsets. Processors read memory fastest, and some only, at addresses that are a multiple of the size of the value. So each type has an alignment, and compilers place each field of a structure at an offset that is a multiple of its alignment, with padding bytes between fields and at the end. C has a macro for the offset: offsetof gives "the offset, in bytes, from the beginning of an object of specified type to its specified subobject, including padding if any."2 Python's ctypes.alignment and Rust's align_of give the alignment of a type.9 Putting the largest fields first reduces padding.

Virtual addresses. A program does not see the numbers of the physical memory chips. The operating system gives each process its own virtual address space, and the memory management unit of the processor translates each virtual address to a physical one through page tables, usually in pages of 4 KiB or more. So two processes can use the same address for different data, a process cannot read the memory of another, and an address that maps to no page causes a fault, such as a segmentation fault. The operating system also places the stack, the heap and the libraries at random addresses on each run, a defense called address space layout randomization, which is why the examples print offsets and not addresses.

From addresses to pointers and references. Languages build safer things on top of addresses. In C, a pointer "is a type of an object that refers to a function or an object of another type", and the operators & and * take an address and follow one.1 Pointer arithmetic counts in elements, not bytes. Go and Rust have pointers too, but rules limit what a program can do with them, and a raw address needs a special path: Go's unsafe.Pointer "allows a program to defeat the type system and read and write arbitrary memory".4 Rust warns that an address alone is not a pointer: "a usize cannot accurately represent a pointer, and converting from a pointer to a usize is generally an operation which only extracts the address."5 A pointer also carries its provenance, the allocation that it may access. Java, C#, JavaScript and Python give references, which name objects but expose no address. See pointers and references.

Moving objects. A compacting garbage collector moves objects to new addresses and updates the references to them, so the address of an object in Java, C# or Go can change while the program runs. An integer that holds an old address is not updated: Go's documentation says that "Even if a uintptr holds the address of some object, the garbage collector will not update that uintptr's value if the object moves, nor will that uintptr keep the object from being reclaimed."4 C# pins an object to stop the collector from moving it while native code uses its address. In CPython objects never move, and id() gives the address: "CPython implementation detail: This is the address of the object in memory."3

Addresses outside the garbage-collected heap. Code that talks to hardware, to files mapped into memory or to libraries in C needs real addresses. Java's foreign memory API gives memory segments with an address() and slices at offsets.6 .NET's Unsafe.ByteOffset "Determines the byte offset from origin to target from the given managed pointers."7 JavaScript has no addresses at all, but an ArrayBuffer is a block of bytes, typed arrays and DataView read it at byte offsets, and DataView reads values "without having to care about the platform's endianness".8

In languages

LanguageVerdictNote
PythonStandard library
C++Native
JavaStandard library
CNative
C#Native
JavaScriptAbsent
TypeScriptAbsentTypeScript has the same runtime as JavaScript, so it has no addresses, and typed arrays and DataView give byte offsets in an ArrayBuffer, but no example file exists.
GoNative
RustNative
KotlinStandard libraryKotlin on the JVM gives references only and can use the foreign memory API of Java, and Kotlin/Native has CPointer for C interop, but no example file exists because kotlinc is not installed.
SQLDoes not applySQL works with rows and keys, and the database engine decides where the data is in memory and on disk.
BashAbsentBash works with strings, files and processes and gives no access to memory or addresses.
PowerShellStandard libraryPowerShell gives references to .NET objects, and the .NET types IntPtr and Marshal read memory at an address, but no example file exists because pwsh is not installed.
HTMLDoes not applyHTML describes a document and has no memory model.
CSSDoes not applyCSS describes presentation and has no memory model.
Regular expressionsDoes not applyA pattern matches text by positions in the text, not by memory addresses.
Language Verdict Mechanism
Python stdlib references only; id() in CPython; ctypes.addressof
JavaScript absent no addresses; byte offsets in an ArrayBuffer
TypeScript absent as JavaScript
Java stdlib references only; the foreign memory API for native memory
Kotlin stdlib references only; the JVM foreign memory API, or Kotlin/Native CPointer
C# native & and pointers in unsafe code; ref; pinning
Go native & and *; unsafe.Pointer, uintptr, unsafe.Offsetof
Rust native references; raw pointers, addr, offset_of!
C native &, *, pointer arithmetic, offsetof, uintptr_t
C++ native as C, with std::addressof and references
Bash absent no access to memory
PowerShell stdlib .NET interop types such as IntPtr
SQL n/a rows and keys, not addresses
Regex n/a positions in text, not addresses
HTML n/a no memory model
CSS n/a no memory model

C and C++ expose addresses as a normal part of the language, and C#, Go and Rust expose them behind a marked unsafe path, so the verdict for these five is native. Python and Java give references in the language and addresses only through the standard library: ctypes and the foreign memory API. JavaScript has no addresses at all, and byte offsets inside an ArrayBuffer are the closest idea. The languages with a moving garbage collector, Java, C# and Go, keep addresses out of normal code so that the collector can move objects.

The example files show the same layout from each language. Python shows identity and a memoryview that shares bytes. JavaScript reads one buffer through views of different sizes and byte orders. Java takes addresses of native memory and checks bounds. C# gets the distance between two array elements and reads through a pinned address. Go measures the distance with uintptr and moves a pointer with unsafe.Add. Rust compares the layout of a repr(C) struct with the default layout, which reorders fields. C uses &, *, pointer arithmetic and offsetof, and C++ shows a vector that moves its elements to a new address.

PythonGitHub
a = [1, 2, 3]
b = a
c = [1, 2, 3]
print("a is b:", a is b, "same id:", id(a) == id(b))
print("a is c:", a is c, "a == c:", a == c)

data = bytearray(b"hello")
view = memoryview(data)[1:4]  # a window on the same bytes, no copy
view[0] = ord("E")
print(data, "view length", view.nbytes)

Output
a is b: True same id: True
a is c: False a == c: True
bytearray(b'hEllo') view length 3
  • Verdict: stdlib. Python code works with references and never sees an address. is compares identity, and id gives a number that is the same for one object while it lives; in CPython it is the address. Two equal lists are different objects. A memoryview is a window on the bytes of another object at an offset, so a write through the view changes the bytearray. The ctypes module in the idea section gives real addresses with addressof.
#include <cstddef>
#include <cstdint>
#include <iostream>
#include <memory>
#include <vector>

int main() {
    std::vector<int> v{10, 20, 30};
    auto before = reinterpret_cast<std::uintptr_t>(v.data()); // keep the address as a number
    v.reserve(1000); // the vector moves its elements to a new block
    auto after = reinterpret_cast<std::uintptr_t>(v.data());
    std::cout << "same block after reserve: " << std::boolalpha << (before == after) << '\n';
    // A pointer kept from before the move would point to freed memory.

    int x = 7;
    int& r = x;     // a reference is another name for the object at an address
    int* p = std::addressof(x);
    std::cout << "&r == p: " << (&r == p) << '\n';

    auto n = reinterpret_cast<std::uintptr_t>(p); // the address as an integer
    std::cout << "aligned to alignof(int): " << (n % alignof(int) == 0) << '\n';

    struct Node { char c; double d; };
    std::cout << "offsetof(Node, d) = " << offsetof(Node, d) << ", sizeof(Node) = " << sizeof(Node) << '\n';
}
Output
same block after reserve: false
&r == p: true
aligned to alignof(int): true
offsetof(Node, d) = 8, sizeof(Node) = 16
  • Verdict: native. C++ has the pointers of C and adds references, which are other names for an object, so &r is the address of x. std::addressof gives the address even for a type that overloads &. A std::vector keeps its elements in one block and moves them to a new block when it grows, so reserve changes data(), and a pointer kept from before would point to freed memory. The double in Node is at offset 8, after 7 bytes of padding.
JavaGitHub
import java.lang.foreign.Arena;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.ValueLayout;

public class Main {
    public static void main(String[] args) {
        // Java objects have no visible address; the garbage collector can move them.
        Object o = new Object();
        Object p = o;
        System.out.println("same object: " + (o == p));

        // The foreign memory API gives native memory with a real address.
        try (Arena arena = Arena.ofConfined()) {
            MemorySegment seg = arena.allocate(ValueLayout.JAVA_INT, 4);
            for (int i = 0; i < 4; i++) seg.setAtIndex(ValueLayout.JAVA_INT, i, (i + 1) * 10);
            MemorySegment slice = seg.asSlice(8);
            System.out.println("slice address - base address = " + (slice.address() - seg.address()));
            System.out.println("int at offset 8: " + seg.get(ValueLayout.JAVA_INT, 8));
            System.out.println("aligned to 4: " + (seg.address() % 4 == 0));
            try {
                seg.get(ValueLayout.JAVA_INT, 16);
            } catch (IndexOutOfBoundsException e) {
                System.out.println("offset 16 is out of bounds");
            }
        }
    }
}
Output
same object: true
slice address - base address = 8
int at offset 8: 30
aligned to 4: true
offset 16 is out of bounds
  • Verdict: stdlib. Java objects have no visible address, and == on references compares identity. The foreign memory API in java.lang.foreign allocates native memory in an arena. A MemorySegment has an address(), a slice at offset 8 starts 8 bytes after the base, and reads at a byte offset are checked, so offset 16 in a segment of 16 bytes throws IndexOutOfBoundsException. Closing the arena frees the memory.
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>

struct rec {
    char flag;
    int32_t count;
    char tag;
};

int main(void) {
    int32_t xs[4] = {10, 20, 30, 40};
    int32_t *p = &xs[0];        /* &: the address of an object */
    int32_t *q = p + 2;         /* pointer arithmetic counts elements, not bytes */
    printf("q - p = %td elements\n", q - p);
    printf("bytes apart: %td\n", (char *)q - (char *)p);
    printf("*q = %d, p[3] = %d\n", *q, p[3]); /* *: the object at an address */

    *q = 99;                    /* write through the address */
    printf("xs[2] = %d\n", xs[2]);

    printf("offsets: %zu %zu %zu, size %zu, align %zu\n",
           offsetof(struct rec, flag), offsetof(struct rec, count),
           offsetof(struct rec, tag), sizeof(struct rec), _Alignof(struct rec));
    printf("p aligned to 4: %d\n", (uintptr_t)p % 4 == 0);
    return 0;
}
Output
q - p = 2 elements
bytes apart: 8
*q = 30, p[3] = 40
xs[2] = 99
offsets: 0 4 8, size 12, align 4
p aligned to 4: 1
  • Verdict: native. & takes the address of an object and * follows one. The difference of two pointers counts elements, and the difference of the same addresses as char * counts bytes. p[3] is *(p + 3), and a write through a pointer changes the array. offsetof, sizeof and _Alignof give the layout, and a cast to uintptr_t gives the address as an integer to check the alignment.
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

int[] xs = [10, 20, 30, 40];
// Managed references are addresses that the runtime updates when the GC moves an array.
nint d = Unsafe.ByteOffset(ref xs[0], ref xs[2]);
Console.WriteLine($"xs[2] is {d} bytes after xs[0]");

Console.WriteLine($"offset of Count: {Marshal.OffsetOf<Rec>(nameof(Rec.Count))}");
Console.WriteLine($"offset of Tag: {Marshal.OffsetOf<Rec>(nameof(Rec.Tag))}");
Console.WriteLine($"size: {Marshal.SizeOf<Rec>()}");

GCHandle h = GCHandle.Alloc(xs, GCHandleType.Pinned); // pinned: the GC must not move it
nint a0 = h.AddrOfPinnedObject();
Console.WriteLine($"read at address + 12: {Marshal.ReadInt32(a0 + 12)}");
h.Free();

[StructLayout(LayoutKind.Sequential)]
struct Rec
{
    public byte Flag;
    public int Count;
    public byte Tag;
}
Output
xs[2] is 8 bytes after xs[0]
offset of Count: 4
offset of Tag: 8
size: 12
read at address + 12: 40
  • Verdict: native. A ref is a managed pointer that the runtime updates when the garbage collector moves the array, and Unsafe.ByteOffset gives the distance between two of them. Marshal.OffsetOf and Marshal.SizeOf give the layout of a struct with sequential layout, which has padding before Count. A pinned GCHandle stops the collector from moving the array, so its address is safe to use until Free. C# also has &, * and pointer arithmetic in unsafe code.
JavaScriptGitHub
const buf = new ArrayBuffer(8); // 8 bytes; JavaScript gives offsets, not addresses
const words = new Uint32Array(buf); // two 4-byte views on the same memory
const bytes = new Uint8Array(buf);
words[0] = 0x11223344;
console.log("bytes:", Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join(" "));

const view = new DataView(buf);
console.log("little-endian read:", view.getUint32(0, true).toString(16));
console.log("big-endian read:   ", view.getUint32(0, false).toString(16));

const tail = new Uint8Array(buf, 4, 4); // byteOffset 4: the second word
tail[0] = 0xff;
console.log("word 1 after a write at offset 4:", words[1]);
Output
bytes: 44 33 22 11 00 00 00 00
little-endian read: 11223344
big-endian read:    44332211
word 1 after a write at offset 4: 255
  • Verdict: absent. JavaScript has no addresses, so the closest idea is a byte offset in an ArrayBuffer. A Uint32Array and a Uint8Array on the same buffer show the bytes of 0x11223344 in little-endian order. A DataView reads at a byte offset in the byte order that the call names, and a write through the byte view at offset 4 changes word 1 of the word view.
package main

import (
	"fmt"
	"unsafe"
)

type Rec struct {
	Flag  byte
	Count int32
	Tag   byte
}

func main() {
	xs := [4]int32{10, 20, 30, 40}
	p0 := &xs[0]
	p2 := &xs[2]
	// uintptr is a plain integer: subtracting two addresses gives a distance in bytes.
	fmt.Println("distance:", uintptr(unsafe.Pointer(p2))-uintptr(unsafe.Pointer(p0)))

	// unsafe.Add moves a pointer by a number of bytes.
	p3 := (*int32)(unsafe.Add(unsafe.Pointer(p0), 12))
	fmt.Println("value 12 bytes after xs[0]:", *p3)

	var r Rec
	fmt.Println("offsets:", unsafe.Offsetof(r.Flag), unsafe.Offsetof(r.Count), unsafe.Offsetof(r.Tag))
	fmt.Println("size:", unsafe.Sizeof(r), "align:", unsafe.Alignof(r))

	s := xs[1:3] // a slice holds the address of its first element
	fmt.Println("slice starts at xs[1]:", unsafe.SliceData(s) == &xs[1])
}
Output
distance: 8
value 12 bytes after xs[0]: 40
offsets: 0 4 8
size: 12 align: 4
slice starts at xs[1]: true
  • Verdict: native. Go has & and * but no pointer arithmetic in normal code. The unsafe package converts a pointer to a uintptr to measure a distance, and unsafe.Add moves a pointer by bytes. unsafe.Offsetof, Sizeof and Alignof give the layout of a struct. unsafe.SliceData gives the pointer to the first element of a slice, which shows that a slice of an array shares its memory.
RustGitHub
use std::mem::{align_of, offset_of, size_of};

#[allow(dead_code)]
#[repr(C)]
struct Rec {
    flag: u8,
    count: i32,
    tag: u8,
}

#[allow(dead_code)]
struct Reordered {
    flag: u8,
    count: i32,
    tag: u8,
}

fn main() {
    let xs: [i32; 4] = [10, 20, 30, 40];
    let p0: *const i32 = &xs[0];
    let p2: *const i32 = &xs[2];
    println!("distance: {} bytes", p2.addr() - p0.addr());
    // Reading through a raw pointer needs unsafe: the compiler cannot check it.
    let v = unsafe { *p0.add(3) };
    println!("value at p0 + 3 elements: {v}");

    println!("repr(C) offsets: {} {} {}", offset_of!(Rec, flag), offset_of!(Rec, count), offset_of!(Rec, tag));
    println!("repr(C) size {} align {}", size_of::<Rec>(), align_of::<Rec>());
    println!("default layout size {}", size_of::<Reordered>()); // Rust may reorder fields
}
Output
distance: 8 bytes
value at p0 + 3 elements: 40
repr(C) offsets: 0 4 8
repr(C) size 12 align 4
default layout size 8
  • Verdict: native. A reference converts to a raw pointer without unsafe, and addr gives its address as a usize, but reading through a raw pointer needs an unsafe block, because the compiler cannot check that p0.add(3) stays in the array. offset_of! gives the offsets of a repr(C) struct, which has the C layout. Without repr(C), the compiler may reorder the fields, and today it puts the two bytes together after the i32, so the struct takes 8 bytes and not 12.
  • Word addressing. Some old machines and some digital signal processors give an address to each word, not each byte.
  • Segmented addresses. The 8086 formed an address from a segment and an offset; protected modes later used segments as a second level of mapping.
  • Tagged and compressed addresses. ARM's top-byte ignore and memory tagging use the high bits of a 64-bit address for metadata, and the JVM can store references as 32-bit compressed offsets.
  • Memory-mapped I/O. Device registers have addresses, so writing to an address can send a command to hardware.
  • Handles and indexes. Many programs refer to objects by an index into an array or by a handle, which stays valid when the storage moves and can be checked.
  • Pointers and references. Pointers and references are the language features built on addresses.

Pitfalls

  • Keeping an address after the storage moves or ends. A pointer into a vector, a string or a slice is invalid after the container grows, and a pointer to a local is invalid after the function returns. See use after free.
  • Computing addresses out of bounds. Arithmetic that goes past the end of an array reads or writes other data. See out-of-bounds read.
  • Treating addresses as stable numbers. Addresses change from run to run because of address space layout randomization, and objects move in garbage-collected languages. Do not print, hash or sort by them where the order matters.
  • Misaligned access. Reading a 4-byte value at an address that is not a multiple of 4 is slow on some processors, faults on others and is undefined behavior in C and C++. Use memcpy to read unaligned data.
  • Assuming a layout. Field order, padding and byte order depend on the compiler, the target and the language. Rust reorders fields unless the type is repr(C). Write files and network data field by field.
  • Confusing elements and bytes. In C, p + 1 moves by one element, not one byte, so code that mixes byte offsets and element offsets lands in the wrong place.

Cost

Computing an address costs one or two machine instructions: a base, plus an index times a size, plus a constant offset. The cost of using it depends on where the data is. A read from the L1 cache takes a few cycles, from main memory about a hundred times longer, and a read that misses the translation cache of the memory management unit adds a walk of the page tables. Data at nearby addresses shares cache lines of 64 bytes, so arrays read in order are fast and pointer-heavy structures that jump around memory are slow. Padding costs memory: a structure with badly ordered fields can be half padding.

History

The EDVAC report of 1945, by John von Neumann, described a memory of numbered words that held both instructions and data, and the stored-program computers built from 1948 used this model. Tom Kilburn and Frederic Williams's Manchester Baby of 1948 had 32 words of memory, each with an address. Early machines addressed words; IBM's System/360 of 1964 made the 8-bit byte the unit of addressing, and most later machines followed.

Fritz-Rudolf Güntsch described virtual memory in 1956, and the Atlas computer at Manchester, from 1962, translated addresses through pages, so that programs saw more memory than the machine had. Address sizes grew from 16 bits in minicomputers to 32 bits in the 1980s and 64 bits in the 2000s. Languages moved the other way: C, from 1972, exposed addresses directly, while Lisp, Smalltalk, Java and their successors hid them behind references and let the garbage collector move objects.

References

  1. Pointer declaration, C reference, cppreference.com, Explanation
  2. offsetof, C reference, cppreference.com, Description
  3. Built-in Functions, Python documentation, id()
  4. Package unsafe, Go standard library documentation, type Pointer
  5. Module ptr, Rust standard library documentation, Provenance, Pointers Vs Integers
  6. Interface MemorySegment, Java SE 25 API documentation, address() and asSlice
  7. Unsafe.ByteOffset Method, .NET API documentation, Definition
  8. DataView, MDN Web Docs, Description
  9. ctypes, A foreign function library for Python, Python documentation, addressof and alignment

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/6D9A12/text.yaml