krahets/hello-algo · error

栈为空

Error message

栈为空

What it means

@panic in peek() of the Zig ArrayStack when the stack is empty. peek() returns items[size-1], which underflows when size == 0, so it aborts with '栈为空' (stack is empty). Note that this stack's pop() does NOT route through peek() — it calls ArrayList.pop directly — so the documented '栈为空' panic is specific to peek(). @panic in Zig aborts the process and cannot be caught.

Source

Thrown at 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. Check isEmpty() before peek(); skip or return a sentinel/default when empty.
  2. Use size() > 0 as the guard condition.
  3. Ensure at least one push precedes the first peek in startup/order-dependent code.
  4. Wrap peek() in a helper that returns ?T or an error instead of panicking.

Example fix

// before: @panics '栈为空' on empty stack
const top = stack.peek();

// after
if (!stack.isEmpty()) {
    const top = stack.peek();
}
Defensive patterns

Strategy: validation

Validate before calling

if (!stack.isEmpty()) {
    const top = stack.peek();
}

Prevention

When it happens

Trigger: Calling peek() on a freshly initialized stack with no pushes; peeking after popping every element; a read step that runs before any push in a startup sequence.

Common situations: Expression evaluators that peek an operator before any value is pushed; undo stacks inspected when empty; misordering initialization so inspection precedes the first push.

Related errors


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