krahets/hello-algo · error
堆疊為空
Error message
堆疊為空
What it means
Unrecoverable Zig @panic from peek() on the linked-list stack. Guard `if (self.size() == 0) @panic("堆疊為空")` runs before `self.stack_top.?.val`, preventing a null optional unwrap. Peeking an empty stack is treated as a caller logic error.
Source
Thrown at zh-hant/codes/zig/chapter_stack_and_queue/linkedlist_stack.zig:46
// 析構函式(釋放記憶體)
pub fn deinit(self: *Self) void {
if (self.mem_arena == null) return;
self.mem_arena.?.deinit();
}
// 獲取堆疊的長度
pub fn size(self: *Self) usize {
return self.stk_size;
}
// 判斷堆疊是否為空
pub fn isEmpty(self: *Self) bool {
return self.size() == 0;
}
// 訪問堆疊頂元素
pub fn peek(self: *Self) T {
if (self.size() == 0) @panic("堆疊為空");
return self.stack_top.?.val;
}
// 入堆疊
pub fn push(self: *Self, num: T) !void {
var node = try self.mem_allocator.create(inc.ListNode(T));
node.init(num);
node.next = self.stack_top;
self.stack_top = node;
self.stk_size += 1;
}
// 出堆疊
pub fn pop(self: *Self) T {
var num = self.peek();
self.stack_top = self.stack_top.?.next;
self.stk_size -= 1;
return num;View on GitHub (pinned to 69932aed18)
Solutions
- Guard with `if (!stk.isEmpty())` before every peek().
- Restructure so peek() runs only inside a branch that already established size() > 0.
- Add a ?T-returning wrapper if empty-top inspection is a legitimate case.
Example fix
// before const top = stk.peek(); // after const top = if (stk.isEmpty()) null else stk.peek();
Defensive patterns
Strategy: validation
Validate before calling
// call BEFORE peek() if (stk.isEmpty()) return null; const top = stk.peek();
Prevention
- Prepend `if (!stk.isEmpty())` to every peek().
- Design evaluators/parsers so the top is only peeked after a guaranteed push.
- Use a ?T-returning wrapper for stacks where empty-top peeking is normal.
When it happens
Trigger: Call peek() on a LinkedListStack never pushed, or popped down to a null top. Also triggered by nested evaluators/parsers that inspect the top before any push or after the final pop.
Common situations: Expression evaluators peeking for a pending operator on an empty operand stack; bracket matchers peeking before pushing; DFS-emulation peeking an empty work stack; tests asserting on the top of a freshly built stack.
Related errors
AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13).
Data as JSON: /api/errors/c907050133407829.
Report an issue: GitHub.