krahets/hello-algo · error

索引越界

Error message

索引越界

What it means

@panic in get(index) of the Zig MyList when the index is outside the live element range. Because index is typed usize (unsigned), the `index < 0` clause is effectively dead code — the real guard is `index >= self.items.len`. A Zig @panic is not catchable; it aborts the process, so callers must validate before calling. get() reads a single element and never changes the list length.

Source

Thrown at 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

  1. Check `index < list.getSize()` (and that the list is non-empty) before get().
  2. Because usize cannot be negative, only validate the upper bound.
  3. Re-fetch getSize() immediately before indexing if the list may have mutated.
  4. For bulk reads, iterate with `for (list.items)` which is bounds-safe by construction.

Example fix

// before: @panics (aborts) when index >= len
const v = list.get(idx);

// after
if (idx < list.getSize()) {
    const v = list.get(idx);
}
Defensive patterns

Strategy: validation

Validate before calling

// usize cannot be negative; validate upper bound only.
if (idx < list.getSize()) {
    const v = list.get(idx);
}

Prevention

When it happens

Trigger: Calling get() on an empty list (len == 0, every index >= 0 panics); index >= items.len after removals shrank the slice; passing a usize computed from an unchecked source.

Common situations: Indexing with a value derived from `items.len` captured before removals; deserialized/parsed index not clamped; assuming the `index < 0` branch protects negatives (impossible for usize).

Related errors


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