krahets/hello-algo · error
スタックが空です
Error message
スタックが空です
What it means
This panic is raised by peek() in a singly-linked-list stack (Japanese localization). It fires when reading the top element while stk_size == 0. The guard prevents a null stack_top dereference. @panic is uncatchable in Zig.
Source
Thrown at ja/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 stack.isEmpty() before peek().
- Loop with while (!stack.isEmpty()) and peek inside.
- Verify size() > 0 before any top access.
- Use a wrapper returning ?T if recoverable semantics are needed.
Example fix
// before var top = stack.peek(); // @panics when empty // after if (stack.isEmpty()) return; var top = stack.peek();
Defensive patterns
Strategy: validation
Validate before calling
// Validate non-empty before reading the top
if (!stack.isEmpty()) {
var top = stack.peek();
} Prevention
- Check stack.isEmpty() before every peek().
- Drive consumption with while (!stack.isEmpty()).
- @panic is uncatchable in Zig — validation is the only defense.
When it happens
Trigger: Calling stack.peek() before any push, or after pop() has removed the last element.
Common situations: Monotone-stack algorithms reading the top when empty; DFS stack checked at the wrong loop point; porting catchable EmptyStackException code.
Related errors
AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13).
Data as JSON: /api/errors/397772e7a7f7915e.
Report an issue: GitHub.