krahets/hello-algo · error

стек пуст

Error message

стек пуст

What it means

This panic is raised by peek() in an array-backed stack using std.ArrayList (Russian localization). It fires when reading items[size-1] while empty — the guard prevents both a meaningless read and an unsigned underflow of the index. Note pop() here uses ArrayList.pop directly (not peek), so this panic is specific to peek(). @panic is uncatchable.

Source

Thrown at ru/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. Loop with while (!stack.isEmpty()) and peek inside.
  3. Cache size() and only peek when > 0.
  4. Note pop() is also unguarded on this impl — check before popping too.

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; i.e., before any push or after the last pop.

Common situations: Empty operator-stack top check; inspecting the top before initialization; peeking once more after a drain loop.

Related errors


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