krahets/hello-algo · error
стек пуст
Error message
стек пуст
What it means
Unrecoverable Zig @panic from peek() on the linked-list stack. The guard `if (self.size() == 0) @panic("стек пуст")` runs before `self.stack_top.?.val`, protecting against dereferencing a null top pointer. Peeking the top of an empty stack is defined by this library as a logic error, not a recoverable case.
Source
Thrown at ru/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().
- Refactor the algorithm so peek() is only reached inside a branch that already established size() > 0.
- Wrap the stack with a peek()-returning-?T adapter if empty-top inspection is normal for your use 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 that has never been pushed, or whose top was popped down to null. Also triggered by nested code (evaluators, parsers) that inspects the top before any push or after the final pop.
Common situations: Expression evaluators that peek for an operator on an empty operand stack; bracket-matching that peeks before pushing the first bracket; recursive-DFS emulation that peeks the work stack after it empties; tests asserting 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/506b25518d0522b9.
Report an issue: GitHub.