D Expert · Lesson 1 · On the house

SafeD: @safe, @trusted, and @system

Memory safety attributes: what @safe forbids, when @trusted bridges, and how @system opts out. Lesson 1 is free — on the house.

Lessons · D Expert · Lesson 1 of 10 · On the house

SafeD: @safe, @trusted, and @system

Memory safety attributes: what @safe forbids, when @trusted bridges, and how @system opts out.

Illustration for D
Lesson 1 is on the house.

@safe is D's memory-safety checker. Inside @safe code you cannot index an array out of bounds without a bounds check, cast away immutable, take the address of a local in ways that escape, call @system functions, or perform other operations the language marks unsafe.

Default for most new code is @system (unchecked). Marking a function @safe opts that function into the checker. Module-level @safe: makes every following declaration safe until another attribute changes it.

@trusted means "this body uses unsafe operations, but its interface is safe to call from @safe code." Use it for thin wrappers around verified pointer work, FFI, or a single checked cast.

@system is the escape hatch: raw pointers, unchecked casts, inline asm. Call it only from @system or @trusted callers.

Inference: templates and nested functions often inherit safety from how they are used. Prefer explicit @safe on public APIs so the type checker, not convention, enforces the boundary.

SafeD

import std.stdio;

@system void poke(int* p, int v) { *p = v; }

@trusted void setFromSafe(ref int x, int v)
{
    poke(&x, v); // trusted may call system; callers stay @safe
}

@safe int add(int a, int b) { return a + b; }

@safe void main()
{
    int x = 3;
    writeln(add(2, x));
    setFromSafe(x, 9);
    writeln(x);
    int[] xs = [1, 2, 3];
    writeln(xs[1]); // bounds-checked in @safe
}
Match this when you type.

Quiz

What may a @safe function not call directly?

Quiz

What does @trusted promise about its interface?

Quiz

What is the default safety attribute for most D functions?

Quiz

What does setFromSafe print as x after the call?

Check

Match the still for: SafeD: @safe, @trusted, and @system.

Open-book: the answers are on this page. Pass every quiz and check (5) to mark the lesson done. This visit: 0/5.