krahets/hello-algo · error

индекс выходит за границы

Error message

индекс выходит за границы

What it means

This panic is raised by get() in a hand-written dynamic array / MyList (Russian localization). It fires when index >= items.len. Because index is usize (unsigned), the `index < 0` branch is dead code — only `index >= self.items.len` can trigger. @panic aborts the process and is not catchable.

Source

Thrown at ru/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. Bounds-check before access: if (idx >= list.getSize()) handle and return.
  2. Iterate with idx < getSize() captured once per loop.
  3. Re-fetch size after any mutation before re-indexing.
  4. Drop the misleading `index < 0` branch for usize clarity.

Example fix

// before
var v = list.get(idx); // @panics when idx >= len

// after
if (idx >= list.getSize()) return;
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

When it happens

Trigger: Calling list.get(idx) with idx at or beyond the current element count; reading from a freshly-cleared or never-populated list.

Common situations: Off-by-one read loops; stale cached size after removals; capacity-vs-length confusion; negative-index expectations ported from Python.

Related errors


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