krahets/hello-algo · error
インデックスが範囲外です
Error message
インデックスが範囲外です
What it means
This panic is raised by get() in a hand-written dynamic array / MyList (Japanese localization). It fires when the supplied index is outside [0, items.len). Note: because index is usize (unsigned), the `index < 0` half of the guard is dead code — only the `index >= self.items.len` check can ever trigger. @panic aborts the process and is not catchable.
Source
Thrown at ja/codes/zig/chapter_array_and_linkedlist/my_list.zig:58
const new_item_ptr = &self.items[self.items.len - 1];
new_item_ptr.* = item;
}
// リストの長さを取得(現在の要素数)
pub fn getSize(self: *Self) usize {
return self.items.len;
}
// リスト容量を取得する
pub fn getCapacity(self: *Self) usize {
return self.capacity;
}
// 要素にアクセス
pub fn get(self: *Self, index: usize) i32 {
// インデックスが範囲外なら例外を送出する。以下同様
if (index < 0 or index >= self.items.len) {
@panic("インデックスが範囲外です");
}
return self.items[index];
}
// 要素を更新
pub fn set(self: *Self, index: usize, num: i32) void {
// インデックスが範囲外なら例外を送出する。以下同様
if (index < 0 or index >= self.items.len) {
@panic("インデックスが範囲外です");
}
self.items[index] = num;
}
// 中間に要素を挿入
pub fn insert(self: *Self, index: usize, item: i32) !void {
if (index < 0 or index >= self.items.len) {
@panic("インデックスが範囲外です");
}View on GitHub (pinned to 69932aed18)
Solutions
- Bounds-check before access: if (idx >= list.getSize()) return early or handle.
- Drive loops with list.getSize() captured once, iterating idx < size.
- Re-fetch the size after any insert/remove mutation before re-indexing.
- Remove the dead `index < 0` branch — it misleads readers about usize semantics.
Example fix
// before
var v = list.get(idx); // @panics when idx >= len
// after
if (idx >= list.getSize()) {
return; // handle out-of-range
}
var v = list.get(idx); Defensive patterns
Strategy: validation
Validate before calling
// Bounds-check before indexed read
if (idx < list.getSize()) {
var v = list.get(idx);
} Prevention
- index is usize — a negative value can never occur; do not write code assuming index < 0 is possible.
- Re-fetch getSize() after any insert/remove before re-indexing.
- Iterate with idx < getSize(), never idx <= getSize().
When it happens
Trigger: Calling list.get(idx) with idx >= current element count, or with idx on a freshly-cleared list.
Common situations: Off-by-one loops (using <= len instead of < len); stale cached length after removes; reading from a list that was shrunk; negative-index expectations ported from Python.
Related errors
AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13).
Data as JSON: /api/errors/3d6418154bbee3c2.
Report an issue: GitHub.