Skip to content
Tutorials Center
My learning

Topics

Lesson 109 of 146 · Advanced Swift

Unsafe Swift

Learn when to use Swift's unsafe pointers: UnsafeMutablePointer, buffer pointers, withUnsafe closures, the memory life cycle, calling C and Span as the safe option.

Almost everything in Swift is memory safe. You cannot read past the end of an array without a crash, you cannot use a variable before it is initialized, and the compiler tracks who owns every object. That safety has a cost in rare situations: you need to hand a block of bytes to a C function, squeeze maximum speed out of a hot loop, parse a binary format in place, or build your own collection type. For those jobs Swift offers the unsafe pointer types.

"Unsafe" does not mean "bad". It means you, not the compiler, promise that the memory is valid, correctly aligned, initialized when read, and still alive when used. If the promise is false, the program has undefined behaviour: it may crash, return garbage, corrupt unrelated data or appear to work until the day it does not. This lesson shows how the pointer family is organized, the life cycle of manually managed memory, the safe withUnsafe… pattern, how to call C, how to wrap a buffer in a type of your own, and, importantly, when to use the safe Span types instead. It builds on Memory layout, so size, stride and alignment should be familiar.

The family of pointer types

The names are systematic. Pick one word from each column:

Word Meaning
Unsafe no safety checks
(nothing) or Mutable read-only, or readable and writable
(nothing) or Raw typed (T), or untyped bytes
Pointer or BufferPointer one address, or an address plus a count

That gives UnsafePointer<T>, UnsafeMutablePointer<T>, UnsafeRawPointer, UnsafeMutableRawPointer, UnsafeBufferPointer<T>, UnsafeMutableBufferPointer<T>, UnsafeRawBufferPointer and UnsafeMutableRawBufferPointer. The buffer variants are the ones to prefer: they know how many elements there are, they conform to Collection (so map, reduce, for … in work) and they check bounds in debug builds. The single-element pointers are what C functions take and return.

The life cycle of memory

Manually managed memory passes through states, and each step has its own call:

  1. allocate(capacity:) reserves space. The memory is uninitialized: it holds garbage and you must not read it.
  2. initialize(to:) (or initialize(repeating:count:)) puts a valid value there. Now it is initialized.
  3. You read and write it through pointee or the subscript.
  4. deinitialize(count:) destroys the values (running deinit for classes, releasing strings and arrays). Now it is uninitialized again.
  5. deallocate() returns the space.

For simple types such as Int steps 2 and 4 look like ceremony, but for types that own something (String, class references, arrays) they are essential: skipping deinitialize leaks, and assigning to memory you have not initialized makes Swift release garbage and crash.

Swift Allocate, initialize, use, deinitialize, deallocate

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The output is 0 10 30 20 followed by 2 true. Notice that pointer + 1 moves forward by one element, which means MemoryLayout<Int>.stride (8) bytes. Pointer arithmetic in Swift is typed, which prevents the most common C mistake of scaling by hand. After deallocate() the pointer still holds an address, but nothing valid lives there. Using it is a classic use after free. Set such pointers to nil or let them go out of scope immediately.

The safe pattern: withUnsafe closures

Most of the time you do not allocate anything. You already have an array, a string or a variable, and you need a pointer to its storage for a moment. The standard library lends one with a closure whose parameter is the pointer. The pointer is valid exactly as long as the closure runs, and you must not let it escape:

Swift Borrowing pointers with withUnsafe closures

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

You see 43, 15, [10, 4, 6, 8, 2] and then 6 104 and 6: the C string function strlen counts bytes, so héllo has 6 (the é takes two in UTF-8), and 104 is the byte for h. withCString gives C a null-terminated copy that lives only for the closure. The other calls show the shape of the whole family: withUnsafeBufferPointer for reading an array's elements, withUnsafeMutableBufferPointer for changing them in place (one exclusive access, no bounds checks per element in optimized builds), withUnsafeMutablePointer(to:) for a single variable.

Never let the pointer escape the closure. Code like the following compiles, but the pointer outlives the buffer it points into, and reading it later is undefined behaviour:

Swift
// Read-only example: this is a BUG. Do not do this.
var saved: UnsafePointer<Int>?
let items = [1, 2, 3]
items.withUnsafeBufferPointer { buffer in
    saved = buffer.baseAddress      // escapes the closure
}
print(saved!.pointee)               // undefined behaviour: the buffer may be gone or moved

Copy the values you need out of the closure (return an Int, an array, a struct), not the pointer.

A read-only pointer is read-only

UnsafePointer cannot write; you need UnsafeMutablePointer. The compiler enforces it, which is a useful way to document intent:

Swift Writing through UnsafePointer (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The error is main.swift:4:11: error: cannot assign to property: 'pointee' is a get-only property. Use var numbers with withUnsafeMutableBufferPointer to change the elements. baseAddress is optional because an empty buffer may have no address; force-unwrap it only after you have checked count.

Typed versus raw memory

A typed pointer says "there are Ints here". A raw pointer says "there are bytes here" and lets you decide how to read them. Moving between the two is where you must understand layout and alignment:

  • load(as:) reads a value of some type from raw memory. The address must be aligned for that type (loadUnaligned relaxes that).
  • storeBytes(of:as:) writes a value into raw memory.
  • bindMemory(to:) tells the compiler "treat these raw bytes as T from now on".
  • withMemoryRebound(to:capacity:) temporarily views typed memory as another type of the same size and layout.
Swift Raw bytes, rebinding and bit patterns

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The first line prints 4 1 67305985: four bytes, the lowest byte is 1 (little-endian), and the whole value read back is 67305985, which is 0x04030201 in decimal. The array of two floats has 8 bytes, and 1.0 has the bit pattern 1065353216 (0x3F800000). Rebinding -1 as unsigned gives 4294967295. The last line is true: a 16-bit value was written at the odd offset 3, then read back with loadUnaligned.

Swift has a strict aliasing rule: you must not access the same memory as two unrelated types at once. withMemoryRebound and bindMemory are the sanctioned ways to switch, and only for types with compatible layouts. For converting a value's bits, prefer safe APIs such as Float.bitPattern, UInt32(truncatingIfNeeded:) and Int32(bitPattern:).

Calling C

Pointers are the language of C. A char * becomes UnsafePointer<CChar>, a void * becomes UnsafeRawPointer, and an out parameter becomes UnsafeMutablePointer. The next example sorts an array with the C library's qsort and then shows three more tools that save an allocation: a temporary stack-style buffer, a bulk copy and an array filled in place.

Swift qsort and other pointer-based tools

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The output is [1, 2, 5, 7, 9], 14 4 (0+1+4+9 and four elements), [1, 2, 3, 4] and [0, 1, 4, 9, 16]. Two things are worth noticing. The comparison closure passed to qsort is a C function pointer: it cannot capture local variables, which is why it only uses its arguments. And in Array(unsafeUninitializedCapacity:) you promise to initialize exactly count elements before returning; if you set count = 5 and only fill 3, the array contains garbage. A forgotten bound is the typical bug here.

Owning a buffer: a small ring buffer

When you build your own collection, you often allocate storage yourself. The rule of thumb is to wrap the raw pointer in a class whose deinit cleans up, so nobody else has to remember. This ring buffer keeps the most recent capacity values and overwrites the oldest:

Swift A ring buffer that owns its memory

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The output proves the memory management is right. freed 1 appears when Tracker 1 is overwritten, freed 2 as soon as the element removed by popFirst is released (before the line is printed), then first out: Optional(2) left: 1, and finally freed 3 when demo() returns and the ring's deinit destroys the one remaining element. Every tracker was freed exactly once. The integer ring prints 3 4 5. The three rules to copy: assign only to initialized slots, initialize uninitialized ones, and make deinit deinitialize exactly the initialized slots before it deallocates.

What goes wrong: undefined behaviour

The compiler cannot check pointer code, so the typical bugs are silent:

  • Use after free / dangling pointer: reading memory after deallocate() or after the closure that lent it returned.
  • Out of bounds: buffer pointers check indexes in debug builds only. In an optimized build, reading buffer[5] of a 3-element buffer just reads whatever lies next to it.
  • Reading uninitialized memory, or forgetting deinitialize, which leaks or double-releases.
  • Misaligned access: load(as:) at an address that does not suit the type.
  • Aliasing violations: treating the same bytes as two unrelated types.
  • Wrong count: Array(unsafeUninitializedCapacity:) with the wrong count, or bindMemory with a capacity bigger than the allocation.

A null pointer is at least loud. UnsafePointer<Int>(bitPattern: 0) correctly returns nil, since pointers cannot be null, and force-unwrapping that nil stops the program:

Swift Force-unwrapping a null pointer (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The program ends with Illegal instruction and a backtrace and no message, because force-unwrapping nil is a trap, and traps print no text in this optimized build. The more dangerous cases are the ones that do not crash.

On a normal toolchain you can look for these bugs with the sanitizers. They are read-only here because the site's compiler runs with fixed options:

Terminal
# Read-only example: needs your own toolchain.
swiftc -sanitize=address main.swift -o app     # catches use-after-free and overflows
swiftc -sanitize=thread  main.swift -o app     # catches data races
swiftc -enforce-exclusivity=checked -Onone main.swift   # checks overlapping access

Span: the safe alternative

Swift 6.2 added Span<T>, MutableSpan<T>, RawSpan and UTF8Span: views over contiguous memory that look like a buffer pointer but are memory safe. Their subscript always checks bounds, and the compiler tracks their lifetime, so a span cannot outlive the array it views. Arrays, ContiguousArray and many other types expose a .span property:

Swift Span: a bounds-checked view with a tracked lifetime

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

You get 15, then 9 (2 + 3 + 4, a sub-view made without copying), then 5 2 Span<Int>, and finally 40: a RawSpan of the five 8-byte integers. Writing span[10] would trap with a bounds error in every build, unlike UnsafeBufferPointer. The lifetime tracking is the second half of the story. A function cannot hand a span of a local array back to its caller, because the array would be gone:

Swift A Span cannot outlive its owner (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The compiler refuses with main.swift:1:22: error: a function cannot return a ~Escapable result. Span is a non-escapable type (~Escapable): it may be passed to functions, stored briefly and used, but not returned or stored beyond the owner's life, without explicit lifetime annotations that the standard library controls. That is precisely the dangling-pointer bug turned into a compile error.

When to use what

  • First choice: neither. Ordinary arrays, strings, Data and loops are fast enough in almost every program. Measure before you reach for pointers.
  • Reading or processing contiguous data safely: Span, RawSpan (Swift 6.2 and newer), or withUnsafeBufferPointer if you must support older compilers.
  • Calling C: withUnsafe…/withCString closures, and keep pointers inside them. See Interoperating with C.
  • Implementing a collection or buffer type: one class or noncopyable struct that owns the allocation and cleans up in deinit.
  • Avoid: storing pointers in properties, returning them, doing arithmetic that is not tied to a known count, and "casting" between unrelated types.
  • Always: keep the unsafe code in a few small, well-tested functions with a safe interface around them.

Check your understanding

Quick check · 5 questions

of 5 answered You scored / 5 · perfect!

  1. 1. What is the correct order of the life cycle for manually allocated typed memory?

    Memory is allocated (uninitialized), then initialized, used, deinitialized (destroying the values) and finally deallocated. Skipping deinitialize leaks values that own resources.
  2. 2. Why must you not store the pointer given to a withUnsafeBufferPointer closure and use it afterwards?

    The array lends its storage only for the duration of the closure. A pointer kept afterwards dangles, and reading it is undefined behaviour.
  3. 3. Which type lets you write through the pointer?

    Only the Mutable variants allow assignment through pointee or the subscript. The plain variants are read-only and the compiler rejects writes.
  4. 4. What does pointer + 2 do for an UnsafeMutablePointer<Int32>?

    Typed pointer arithmetic counts elements, scaled by the type's stride. Int32 has stride 4, so two elements is 8 bytes.
  5. 5. What is the main safety advantage of Span over UnsafeBufferPointer?

    Span checks bounds in every build and is non-escapable, so the lifetime of the view is tied to the memory it views at compile time.

Summary

  • The unsafe pointer types follow a naming scheme: Unsafe + optional Mutable + optional Raw + Pointer or BufferPointer.
  • Manual memory goes through allocate, initialize, use, deinitialize, deallocate; assign only to initialized slots.
  • Prefer the withUnsafe… closures and never let the pointer escape; typed pointer arithmetic is counted in elements.
  • Use load(as:), storeBytes, bindMemory and withMemoryRebound carefully, with attention to alignment and aliasing.
  • Wrap raw allocations in a class whose deinit cleans up, and keep the unsafe surface small.
  • Mistakes are undefined behaviour, not errors: use sanitizers on a real toolchain.
  • Span and RawSpan give pointer-like speed with bounds checks and compile-time lifetimes; prefer them where available.

Next: Interoperating with C