Z030: deinit should set self.* = undefined
Detects deinit functions with pointer receivers that neither set the receiver
to undefined nor end its lifetime with destroy(receiver). The diagnostic
uses the receiver's actual parameter name, such as self.* or value.*.
Invalidating a caller-owned receiver is a Zig convention that helps catch
use-after-free bugs during development.
Examples
Bad
Missing self.* = undefined:
// expect: Z030
const Foo = struct {
data: []u8,
allocator: std.mem.Allocator,
fn deinit(self: *Foo) void {
self.allocator.free(self.data);
}
};
Early return without defer:
// expect: Z030
const Foo = struct {
data: ?[]u8,
allocator: std.mem.Allocator,
fn deinit(self: *Foo) void {
if (self.data == null) return;
self.allocator.free(self.data.?);
self.* = undefined;
}
};Good
Set self.* = undefined at the end:
const Foo = struct {
data: []u8,
allocator: std.mem.Allocator,
fn deinit(self: *Foo) void {
self.allocator.free(self.data);
self.* = undefined;
}
};
Use defer to handle all code paths:
const Foo = struct {
data: ?[]u8,
allocator: std.mem.Allocator,
fn deinit(self: *Foo) void {
defer self.* = undefined;
if (self.data) |d| {
self.allocator.free(d);
}
}
};
Heap-allocated receivers may end their lifetime by destroying themselves. In that case, no invalidating write is needed:
const Foo = struct {
fn deinit(self: *Foo, allocator: std.mem.Allocator) void {
allocator.destroy(self);
}
};
If both operations are used, invalidation must happen before destruction and the allocator must not be read from the invalidated receiver:
const Foo = struct {
allocator: std.mem.Allocator,
fn deinit(self: *Foo) void {
const allocator = self.allocator;
self.* = undefined;
allocator.destroy(self);
}
};
Non-pointer receivers are not checked:
const Foo = struct {
data: u32,
fn deinit(self: Foo) void {
_ = self;
}
};Rationale
Setting self.* = undefined after deinitialization is a Zig idiom that helps catch use-after-free bugs:
- Debug safety: In debug builds, accessing
undefinedmemory triggers a panic, making bugs immediately visible - Valgrind/ASan friendly: Undefined memory is more likely to be detected by memory sanitizers
- Convention: This pattern is used throughout the Zig standard library
When a deinit function has early returns, using
defer self.* = undefined; ensures all code paths properly invalidate the
struct. Do not use this pattern when the function destroys self: the
deferred write would run after the receiver's allocation has been freed.
An early-return branch that explicitly invalidates the receiver before returning is also accepted.