krahets/hello-algo · error

スタックが空です

Error message

スタックが空です

What it means

This panic is raised by peek() in an array-backed stack built on std.ArrayList (Japanese localization). It fires when reading items[size-1] while the stack is empty (size 0), which would also underflow the index. The guard prevents both a meaningless read and an unsigned underflow. @panic is uncatchable in Zig.

Source

Thrown at ja/codes/zig/chapter_stack_and_queue/array_stack.zig:40

        // デストラクタ(メモリを解放)
        pub fn deinit(self: *Self) void {
            if (self.stack == null) return;
            self.stack.?.deinit();
        }

        // スタックの長さを取得
        pub fn size(self: *Self) usize {
            return self.stack.?.items.len;
        }

        // スタックが空かどうかを判定
        pub fn isEmpty(self: *Self) bool {
            return self.size() == 0;
        }

        // スタックトップの要素にアクセス
        pub fn peek(self: *Self) T {
            if (self.isEmpty()) @panic("スタックが空です");
            return self.stack.?.items[self.size() - 1];
        }  

        // プッシュ
        pub fn push(self: *Self, num: T) !void {
            try self.stack.?.append(num);
        } 

        // ポップ
        pub fn pop(self: *Self) T {
            var num = self.stack.?.pop();
            return num;
        } 

        // ArrayList を返す
        pub fn toList(self: *Self) std.ArrayList(T) {
            return self.stack.?;
        }

View on GitHub (pinned to 69932aed18)

Solutions

  1. Guard with stack.isEmpty() before peek().
  2. Cache stack.size() and only peek when > 0.
  3. Loop with while (!stack.isEmpty()) and peek inside.
  4. Be aware pop() on this implementation does not guard — also check before popping.

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

When it happens

Trigger: Calling stack.peek() when stack.?.items.len == 0; note pop() here does NOT call peek() (it uses ArrayList.pop directly), so this panic is specific to peek().

Common situations: Reading the top to decide precedence in an empty operator stack; checking the top before the first push; iterating until empty then peeking once more.

Related errors


AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13). Data as JSON: /api/errors/c09d1e6cfe3390de. Report an issue: GitHub.