krahets/hello-algo · error

очередь пуста

Error message

очередь пуста

What it means

Unrecoverable Zig @panic from peek() on the singly-linked-list queue. The guard is `if (self.size() == 0) @panic("очередь пуста")` executed before `self.front.?.val`; it prevents a null dereference when the queue holds no nodes. The queue returns the front value without removing it, and an empty peek is treated as a caller bug.

Source

Thrown at ru/codes/zig/chapter_stack_and_queue/linkedlist_queue.zig:48

        // Деструктор (освобождение памяти)
        pub fn deinit(self: *Self) void {
            if (self.mem_arena == null) return;
            self.mem_arena.?.deinit();
        }

        // Получение длины очереди
        pub fn size(self: *Self) usize {
            return self.que_size;
        }

        // Проверка, пуста ли очередь
        pub fn isEmpty(self: *Self) bool {
            return self.size() == 0;
        }

        // Доступ к элементу в начале очереди
        pub fn peek(self: *Self) T {
            if (self.size() == 0) @panic("очередь пуста");
            return self.front.?.val;
        }  

        // Поместить в очередь
        pub fn push(self: *Self, num: T) !void {
            // Добавить num после хвостового узла
            var node = try self.mem_allocator.create(inc.ListNode(T));
            node.init(num);
            // Если очередь пуста, сделать так, чтобы и head, и tail указывали на этот узел
            if (self.front == null) {
                self.front = node;
                self.rear = node;
            // Если очередь не пуста, добавить этот узел после хвостового узла
            } else {
                self.rear.?.next = node;
                self.rear = node;
            }
            self.que_size += 1;

View on GitHub (pinned to 69932aed18)

Solutions

  1. Check `q.isEmpty()` (or `q.size() > 0`) immediately before peek().
  2. Restructure the consumer loop to dequeue (not peek) until isEmpty, so no peek can run at size 0.
  3. Provide a wrapper that returns ?T for callers that legitimately face an empty queue.

Example fix

// before
const head = q.peek();
// after
const head = if (q.isEmpty()) null else q.peek();
Defensive patterns

Strategy: validation

Validate before calling

// call BEFORE peek()
if (q.isEmpty()) return null;
const head = q.peek();

Prevention

When it happens

Trigger: Call peek() on a LinkedListQueue that has had zero pushes, or whose front==null because all elements were dequeued. Also hit by helper code that peeks before the first enqueue.

Common situations: Polling a queue before a producer has enqueued anything; BFS/level-order traversal that peeks the queue after draining the last node; reporting the queue head in logs/UI without a size check.

Related errors


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