krahets/hello-algo · error

キューが空です

Error message

キューが空です

What it means

This panic is raised by peek() in an array-backed circular queue (Japanese localization). It fires when reading the front element while isEmpty() is true. The array queue uses front/size pointers over a fixed-capacity ring buffer; peeking with zero elements has no valid slot. pop() calls peek() internally, so pop-on-empty also surfaces here. @panic is uncatchable.

Source

Thrown at ja/codes/zig/chapter_stack_and_queue/array_queue.zig:77

            // 剰余演算により、rear が配列末尾を越えた後に先頭へ戻るようにする
            var rear = (self.front + self.queSize) % self.capacity();
            // 末尾ノードの後ろに num を追加
            self.nums[rear] = num;
            self.queSize += 1;
        } 

        // デキュー
        pub fn pop(self: *Self) T {
            var num = self.peek();
            // 先頭ポインタを1つ後ろへ進め、末尾を越えたら配列先頭に戻す
            self.front = (self.front + 1) % self.capacity();
            self.queSize -= 1;
            return num;
        } 

        // キュー先頭の要素にアクセス
        pub fn peek(self: *Self) T {
            if (self.isEmpty()) @panic("キューが空です");
            return self.nums[self.front];
        } 

        // 配列を返す
        pub fn toArray(self: *Self) ![]T {
            // 有効長の範囲内のリスト要素のみを変換
            var res = try self.mem_allocator.alloc(T, self.size());
            @memset(res, @as(T, 0));
            var i: usize = 0;
            var j: usize = self.front;
            while (i < self.size()) : ({ i += 1; j += 1; }) {
                res[i] = self.nums[j % self.capacity()];
            }
            return res;
        }
    };
}

View on GitHub (pinned to 69932aed18)

Solutions

  1. Check queue.isEmpty() before peek() or pop().
  2. Drive consumption with while (queue.size() > 0).
  3. Decouple the consumer so it only pops when size() > 0.
  4. If pop() must be safe, wrap it: if (!isEmpty()) pop();

Example fix

// before
var v = queue.pop(); // internally peeks → @panics when empty

// after
if (queue.isEmpty()) return;
var v = queue.pop();
Defensive patterns

Strategy: validation

Validate before calling

// Validate non-empty before peek/pop
if (!queue.isEmpty()) {
    var v = queue.peek();
    _ = queue.pop();
}

Prevention

When it happens

Trigger: Calling queue.peek() or queue.pop() on an empty queue — i.e., capacity allocated but queSize == 0, or after draining all enqueued items.

Common situations: Ring-buffer producer/consumer where the consumer polls faster than the producer; calling pop() in a for-loop bound by capacity rather than by size(); forgetting that pop() delegates to peek().

Related errors


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