ziglang/zig
261
6.0k
Fork
You've already forked zig
772

Repeated access of null field via pointer is no longer null #30985

Closed
opened 2026年01月24日 08:51:35 +01:00 by xiexingwu · 4 comments

Zig Version

0.16.0-dev.2296+fd3657bf8

Steps to Reproduce and Observed Behavior

This is the minimal working example I've managed to trim down to. It does rely on my own implementation of a slot map, but I don't think the implementation is the issue.

conststd=@import("std");constSlotMap=@import("SlotMap.zig").SlotMap;constFooMap=SlotMap(Foo);constFoo=struct{bar:usize,baz:?FooMap.Key,};pubfnmain(init:std.process.Init)!void{constarena=init.arena.allocator();varmap:FooMap=try.initCapacity(arena,1);constfoo_in:Foo=.{.bar=69,.baz=null};constkey_in=trymap.insertBounded(foo_in);constfoo_out_ptr_maybe=map.get(key_in);constfoo_out_ptr=foo_out_ptr_maybe.?;std.debug.assert(foo_out_ptr.baz==null);// Assertion succeedsif(foo_out_ptr.baz==null){std.debug.print("1) baz is null.\n",.{});// This prints}if(foo_out_ptr.baz==null){std.debug.print("2) baz is null.\n",.{});// This does not print}std.debug.assert(foo_out_ptr.baz==null);// Assertion fails}
//! Slot map implementation (Trimmed down)conststd=@import("std");pubfnSlotMap(comptimeT:type)type{returnstruct{constSelf=@This();/// The underlying data structure for the contiguous block of memory.slots:std.ArrayList(Slot),/// Index of `slots` that will be used on the next call of `insert`./// This will be null when the SlotMap is full.free_head:?usize,/// The number of active slotssize:usize,pubconstKey=struct{index:usize,generation:usize,};constSlot=struct{/// Even = vacant, Odd = occupied. Does not necessarily start at 0.generation:usize,content:union(enum){data:T,next_free:?usize,},};/// Initialises the underlying memory to have capacity equal to exactly num elements.pubfninitCapacity(allocator:std.mem.Allocator,num:usize)!Self{return.{.slots=trystd.ArrayList(Slot).initCapacity(allocator,num),.free_head=0,.size=0,};}/// Deinit the underlying memory.pubfndeinit(slot_map:*Self,allocator:std.mem.Allocator)void{slot_map.slots.deinit(allocator);}/// Attempt to insert a value and return the key for later retrieval.pubfninsertBounded(slot_map:*Self,value:T)!Key{constfree_head=slot_map.free_headorelsereturnerror.OutOfMemory;constslots=&slot_map.slots;varslot:*Slot=undefined;if(free_head>=slots.items.len){slot=tryslots.addOneBounded();// If this activates a previously invalidated slot,// ensure the generation is even to reflect it is free.slot.generation+%=slot.generation%2;// set free_headslot_map.free_head=if(free_head==slots.capacity)nullelsefree_head+1;}else{slot=&slots.items[free_head];// Assert this free slot is free, and that it points to a free slot{std.debug.assert(slot.generation%2==0);std.debug.assert(slot.content==.next_free);std.debug.assert(slots.items[slot.content.next_free.?].generation%2==0);}slot_map.free_head=slot.content.next_free;}slot.content=.{.data=value};slot.generation+%=1;slot_map.size+=1;return.{.index=free_head,.generation=slot.generation,};}/// Returns a reference to the value corresponding to the key if it is valid.pubfnget(slot_map:Self,key:Key)?*T{// Check if the slot is currently invalidatedif(key.index>=slot_map.slots.items.len)returnnull;varslot=slot_map.slots.items[key.index];// Check generationif(slot.generation!=key.generation)returnnull;return&slot.content.data;}};}

Output:

zig build run
1) baz is null.
thread 3578515 panic: reached unreachable code
/Users/xiexingwu/.zvm/master/lib/std/debug.zig:419:14: 0x1000756d3 in assert (zig_null)
 if (!ok) unreachable; // assertion failure
 ^
/Users/xiexingwu/src/misc/zig-null/src/main.zig:28:21: 0x10016bb57 in main (zig_null)
 std.debug.assert(foo_out_ptr.baz == null); // Assertion fails
...

Expected Behavior

I expect both assertions to succeed, and for the program to print

1) baz is null.
2) baz is null.
### Zig Version 0.16.0-dev.2296+fd3657bf8 ### Steps to Reproduce and Observed Behavior This is the minimal working example I've managed to trim down to. It does rely on my own implementation of a slot map, but I don't think the implementation is the issue. ```zig const std = @import("std"); const SlotMap = @import("SlotMap.zig").SlotMap; const FooMap = SlotMap(Foo); const Foo = struct { bar: usize, baz: ?FooMap.Key, }; pub fn main(init: std.process.Init) !void { const arena = init.arena.allocator(); var map: FooMap = try .initCapacity(arena, 1); const foo_in: Foo = .{ .bar = 69, .baz = null }; const key_in = try map.insertBounded(foo_in); const foo_out_ptr_maybe = map.get(key_in); const foo_out_ptr = foo_out_ptr_maybe.?; std.debug.assert(foo_out_ptr.baz == null); // Assertion succeeds if (foo_out_ptr.baz == null) { std.debug.print("1) baz is null.\n", .{}); // This prints } if (foo_out_ptr.baz == null) { std.debug.print("2) baz is null.\n", .{}); // This does not print } std.debug.assert(foo_out_ptr.baz == null); // Assertion fails } ``` ```zig //! Slot map implementation (Trimmed down) const std = @import("std"); pub fn SlotMap(comptime T: type) type { return struct { const Self = @This(); /// The underlying data structure for the contiguous block of memory. slots: std.ArrayList(Slot), /// Index of `slots` that will be used on the next call of `insert`. /// This will be null when the SlotMap is full. free_head: ?usize, /// The number of active slots size: usize, pub const Key = struct { index: usize, generation: usize, }; const Slot = struct { /// Even = vacant, Odd = occupied. Does not necessarily start at 0. generation: usize, content: union(enum) { data: T, next_free: ?usize, }, }; /// Initialises the underlying memory to have capacity equal to exactly num elements. pub fn initCapacity(allocator: std.mem.Allocator, num: usize) !Self { return .{ .slots = try std.ArrayList(Slot).initCapacity(allocator, num), .free_head = 0, .size = 0, }; } /// Deinit the underlying memory. pub fn deinit(slot_map: *Self, allocator: std.mem.Allocator) void { slot_map.slots.deinit(allocator); } /// Attempt to insert a value and return the key for later retrieval. pub fn insertBounded(slot_map: *Self, value: T) !Key { const free_head = slot_map.free_head orelse return error.OutOfMemory; const slots = &slot_map.slots; var slot: *Slot = undefined; if (free_head >= slots.items.len) { slot = try slots.addOneBounded(); // If this activates a previously invalidated slot, // ensure the generation is even to reflect it is free. slot.generation +%= slot.generation % 2; // set free_head slot_map.free_head = if (free_head == slots.capacity) null else free_head + 1; } else { slot = &slots.items[free_head]; // Assert this free slot is free, and that it points to a free slot { std.debug.assert(slot.generation % 2 == 0); std.debug.assert(slot.content == .next_free); std.debug.assert(slots.items[slot.content.next_free.?].generation % 2 == 0); } slot_map.free_head = slot.content.next_free; } slot.content = .{ .data = value }; slot.generation +%= 1; slot_map.size += 1; return .{ .index = free_head, .generation = slot.generation, }; } /// Returns a reference to the value corresponding to the key if it is valid. pub fn get(slot_map: Self, key: Key) ?*T { // Check if the slot is currently invalidated if (key.index >= slot_map.slots.items.len) return null; var slot = slot_map.slots.items[key.index]; // Check generation if (slot.generation != key.generation) return null; return &slot.content.data; } }; } ``` Output: ``` zig build run 1) baz is null. thread 3578515 panic: reached unreachable code /Users/xiexingwu/.zvm/master/lib/std/debug.zig:419:14: 0x1000756d3 in assert (zig_null) if (!ok) unreachable; // assertion failure ^ /Users/xiexingwu/src/misc/zig-null/src/main.zig:28:21: 0x10016bb57 in main (zig_null) std.debug.assert(foo_out_ptr.baz == null); // Assertion fails ... ``` ### Expected Behavior I expect both assertions to succeed, and for the program to print ``` 1) baz is null. 2) baz is null. ```

I suspect it's a bug with direct field access via pointer.
Here are two working alternatives:

  1. Explicitly dereference the pointer before accessing the field.
  2. Automatic field reference once, and assign it to a const.
constfoo_out=foo_out_ptr_maybe.?.*;std.debug.assert(foo_out.baz==null);// Assertion succeedsif(foo_out.baz==null){std.debug.print("1) baz is null.\n",.{});// This prints}if(foo_out.baz==null){std.debug.print("2) baz is null.\n",.{});// This now prints}std.debug.assert(foo_out.baz==null);// Assertion now succeeds
constbaz=foo_out_ptr.baz;std.debug.assert(baz==null);// Assertion succeedsif(baz==null){std.debug.print("1) baz is null.\n",.{});// This prints}if(baz==null){std.debug.print("2) baz is null.\n",.{});// This now prints}std.debug.assert(baz==null);// Assertion now succeeds
I suspect it's a bug with direct field access via pointer. Here are two working alternatives: 1) Explicitly dereference the pointer before accessing the field. 2) Automatic field reference *once*, and assign it to a const. ```zig const foo_out = foo_out_ptr_maybe.?.*; std.debug.assert(foo_out.baz == null); // Assertion succeeds if (foo_out.baz == null) { std.debug.print("1) baz is null.\n", .{}); // This prints } if (foo_out.baz == null) { std.debug.print("2) baz is null.\n", .{}); // This now prints } std.debug.assert(foo_out.baz == null); // Assertion now succeeds ``` ```zig const baz = foo_out_ptr.baz; std.debug.assert(baz == null); // Assertion succeeds if (baz == null) { std.debug.print("1) baz is null.\n", .{}); // This prints } if (baz == null) { std.debug.print("2) baz is null.\n", .{}); // This now prints } std.debug.assert(baz == null); // Assertion now succeeds ```
xiexingwu changed title from (削除) Repeated access of null field is no longer null (削除ここまで) to Repeated access of null field via pointer is no longer null 2026年01月24日 08:59:35 +01:00

The problem is in your get function.

pubfnget(slot_map:Self,key:Key)?*T{if(key.index>=slot_map.slots.items.len)returnnull;// You create a local copy of the slot// FIX: var slot = &slot_map.slots.items[key.index];varslot=slot_map.slots.items[key.index];if(slot.generation!=key.generation)returnnull;// You return a pointer to a local variable// FIX: return slot.content.data;return&slot.content.data;}
The problem is in your `get` function. ```zig pub fn get(slot_map: Self, key: Key) ?*T { if (key.index >= slot_map.slots.items.len) return null; // You create a local copy of the slot // FIX: var slot = &slot_map.slots.items[key.index]; var slot = slot_map.slots.items[key.index]; if (slot.generation != key.generation) return null; // You return a pointer to a local variable // FIX: return slot.content.data; return &slot.content.data; } ```

Adding to Littleote's response. The reason why assertion fails is because the call to function std.debug.assert overrides the use-after-return value and it is no longer null.

Adding to Littleote's response. The reason why assertion fails is because the call to function `std.debug.assert` overrides the use-after-return value and it is no longer null.

Relevant issue is https://github.com/ziglang/zig/issues/23528

(in the future, please direct questions to one of the community spaces before coming to the issue tracker)

Relevant issue is https://github.com/ziglang/zig/issues/23528 (in the future, please direct questions to [one of the community spaces](https://ziglang.org/community/) before coming to the issue tracker)
squeek502 2026年01月24日 12:12:10 +01:00
  • closed this issue
  • added
    question
    and removed
    bug
    labels
Sign in to join this conversation.
No Branch/Tag specified
master
elfv2
spork8
restricted
0.16.x
panic-rewrite
parking-futex-lockfree
windows-Io-cleanup
Io-watch
ParseCommandLineOptions
windows-async-files
poll-ring
debug-file-leaks-differently
debug-file-leaks
ProcessPrng
elfv2-dyn
jobserver
threadtheft
io-threaded-no-queue
0.15.x
Io.net
comptime-allocator
restricted-function-pointers
cli
wasm-linker-writer
wrangle-writer-buffering
sha1-stream
async-await-demo
fixes
0.14.x
ast-node-methods
macos-debug-info
make-vs-configure
fuzz-macos
sans-aro
ArrayList-reserve
incr-bug
llvm-ir-nosanitize-metadata
ci-tarballs
ci-scripts
threadpool
0.12.x
new-pkg-hash
json-diagnostics
more-doctests
rework-comptime-mutation
0.11.x
ci-perf-comment
stage2-async
0.10.x
autofix
0.9.x
aro
hcs
0.8.x
0.7.x
0.16.0
0.15.2
0.15.1
0.15.0
0.14.1
0.14.0
0.12.1
0.13.0
0.12.0
0.11.0
0.10.1
0.10.0
0.9.1
0.9.0
0.8.1
0.8.0
0.7.1
0.7.0
0.6.0
0.5.0
0.4.0
0.3.0
0.2.0
0.1.1
0.1.0
Labels
Clear labels
abi/f32
abi/ilp32
abi/sf
accepted
This proposal is planned.
arch/21k
arch/6502
arch/aarch64
arch/alpha
arch/amdgcn
arch/arc
arch/arc32
arch/arc64
arch/arm
arch/avr
arch/bfin
arch/bpf
arch/colossus
arch/cris
arch/csky
arch/dlx
arch/epiphany
arch/fr30
arch/frv
arch/hexagon
arch/hppa
arch/hppa64
arch/ia64
arch/kalimba
arch/kvx
arch/lanai
arch/lm32
arch/loongarch32
arch/loongarch64
arch/m32r
arch/m68k
arch/m88k
arch/mcore
arch/microblaze
arch/mips
arch/mips64
arch/mmix
arch/moxie
arch/mrisc32
arch/msp430
arch/nds32
arch/ns32k
arch/nvptx
arch/or1k
arch/powerpc
arch/powerpc64
arch/propeller
arch/riscv32
arch/riscv64
arch/rl78
arch/rx
arch/s390x
arch/sh
arch/sparc
arch/sparc64
arch/spirv
arch/spu
arch/tricore
arch/v850
arch/vax
arch/vc4
arch/ve
arch/wasm
arch/x86
arch/x86_64
arch/xcore
arch/xtensa
autodoc
The web application for interactive documentation and generation of its assets.
backend/c
The C backend outputs C source code.
backend/llvm
The LLVM backend outputs an LLVM bitcode module.
backend/self-hosted
The self-hosted backends produce machine code directly.
binutils
Zig's included binary utilities: zig ar, zig dlltool, zig lib, zig ranlib, zig objcopy, and zig rc.
breaking
Implementing this issue could cause existing code to no longer compile or have different behavior.
build system
The Zig build system - zig build, std.Build, the build runner, and package management.
debug info
An issue related to debug information (e.g. DWARF) produced by the Zig compiler.
docs
An issue with documentation, e.g. the language reference or standard library doc comments.
error message
This issue points out an error message that is unhelpful and should be improved.
frontend
Tokenization, parsing, AstGen, ZonGen, Sema, Legalize, and Liveness.
fuzzing
An issue related to Zig's integrated fuzz testing.
incremental
Reuse of internal compiler state for faster compilation.
lib/c
This issue relates to Zig's libc implementation and/or vendored libcs.
lib/compiler-rt
This issue relates to Zig's compiler-rt library.
lib/cxx
This issue relates to Zig's vendored libc++ and/or libc++abi.
lib/std
This issue relates to Zig's standard library.
lib/tsan
This issue relates to Zig's vendored libtsan.
lib/ubsan-rt
This issue relates to Zig's ubsan-rt library.
lib/unwind
This issue relates to Zig's vendored libunwind.
linking
Zig's integrated object file and incremental linker.
miscompilation
The compiler reports success but produces semantically incorrect code.
os/android
os/contiki
os/dragonfly
os/driverkit
os/emscripten
os/freebsd
os/fuchsia
os/haiku
os/hermit
os/hurd
os/illumos
os/ios
os/linux
os/maccatalyst
os/macos
os/managarm
os/netbsd
os/ohos
os/openbsd
os/plan9
os/redox
os/rtems
os/serenity
os/tvos
os/uefi
os/visionos
os/wasi
os/watchos
os/windows
proposal
This issue suggests language modifications. If it also has the "accepted" label then it is planned.
release notes
This issue or pull request should be mentioned in the release notes.
testing
This issue is related to testing the compiler, standard library, or other parts of Zig.
zig cc
Zig as a drop-in C-family compiler.
zig fmt
The Zig source code formatter.
zig reduce
The Zig source code reduction tool.
bounty
https://ziglang.org/news/announcing-donor-bounties
bug
Observed behavior contradicts documented or intended behavior.
contributor-friendly
This issue is limited in scope and/or knowledge of project internals.
downstream
An issue with a third-party project that uses this project.
enhancement
Solving this issue will likely involve adding new logic or components to the codebase.
infra
An issue related to project infrastructure, e.g. continuous integration.
optimization
A task to improve performance and/or resource usage.
question
No questions on the issue tracker; use a community space instead.
regression
Something that used to work in a previous version stopped working
upstream
An issue with a third-party project that this project uses.
use case
Describes a real use case that is difficult or impossible, but does not propose a solution.
No labels
abi/f32
abi/ilp32
abi/sf
accepted
arch/21k
arch/6502
arch/aarch64
arch/alpha
arch/amdgcn
arch/arc
arch/arc32
arch/arc64
arch/arm
arch/avr
arch/bfin
arch/bpf
arch/colossus
arch/cris
arch/csky
arch/dlx
arch/epiphany
arch/fr30
arch/frv
arch/hexagon
arch/hppa
arch/hppa64
arch/ia64
arch/kalimba
arch/kvx
arch/lanai
arch/lm32
arch/loongarch32
arch/loongarch64
arch/m32r
arch/m68k
arch/m88k
arch/mcore
arch/microblaze
arch/mips
arch/mips64
arch/mmix
arch/moxie
arch/mrisc32
arch/msp430
arch/nds32
arch/ns32k
arch/nvptx
arch/or1k
arch/powerpc
arch/powerpc64
arch/propeller
arch/riscv32
arch/riscv64
arch/rl78
arch/rx
arch/s390x
arch/sh
arch/sparc
arch/sparc64
arch/spirv
arch/spu
arch/tricore
arch/v850
arch/vax
arch/vc4
arch/ve
arch/wasm
arch/x86
arch/x86_64
arch/xcore
arch/xtensa
autodoc
backend/c
backend/llvm
backend/self-hosted
binutils
breaking
build system
debug info
docs
error message
frontend
fuzzing
incremental
lib/c
lib/compiler-rt
lib/cxx
lib/std
lib/tsan
lib/ubsan-rt
lib/unwind
linking
miscompilation
os/android
os/contiki
os/dragonfly
os/driverkit
os/emscripten
os/freebsd
os/fuchsia
os/haiku
os/hermit
os/hurd
os/illumos
os/ios
os/linux
os/maccatalyst
os/macos
os/managarm
os/netbsd
os/ohos
os/openbsd
os/plan9
os/redox
os/rtems
os/serenity
os/tvos
os/uefi
os/visionos
os/wasi
os/watchos
os/windows
proposal
release notes
testing
zig cc
zig fmt
zig reduce
bounty
bug
contributor-friendly
downstream
enhancement
infra
optimization
question
regression
upstream
use case
Milestone
Clear milestone
No items
No milestone
Projects
Clear projects
No items
No project
Assignees
Clear assignees
No assignees
4 participants
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
ziglang/zig#30985
Reference in a new issue
ziglang/zig
No description provided.
Delete branch "%!s()"

Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?