krahets/hello-algo · error

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

Error message

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

What it means

Russian localization of the removeVertex bounds check (see error 601). Vertices are positional in a contiguous array, so an index outside [0, graph->size) is rejected; stderr is written and the function returns void with no status.

Source

Thrown at ru/codes/c/chapter_graph/graph_adjacency_matrix.c:54

/* Добавление вершины */
void addVertex(GraphAdjMat *graph, int val) {
    if (graph->size == MAX_SIZE) {
        fprintf(stderr, "Количество вершин графа уже достигло максимума\n");
        return;
    }
    // Добавить n-ю вершину и обнулить n-ю строку и столбец
    int n = graph->size;
    graph->vertices[n] = val;
    for (int i = 0; i <= n; i++) {
        graph->adjMat[n][i] = graph->adjMat[i][n] = 0;
    }
    graph->size++;
}

/* Удаление вершины */
void removeVertex(GraphAdjMat *graph, int index) {
    if (index < 0 || index >= graph->size) {
        fprintf(stderr, "индекс вершины выходит за границы\n");
        return;
    }
    // Удалить вершину с индексом index из списка вершин
    for (int i = index; i < graph->size - 1; i++) {
        graph->vertices[i] = graph->vertices[i + 1];
    }
    // Удалить строку с индексом index из матрицы смежности
    for (int i = index; i < graph->size - 1; i++) {
        for (int j = 0; j < graph->size; j++) {
            graph->adjMat[i][j] = graph->adjMat[i + 1][j];
        }
    }
    // Удалить столбец с индексом index из матрицы смежности
    for (int i = 0; i < graph->size; i++) {
        for (int j = index; j < graph->size - 1; j++) {
            graph->adjMat[i][j] = graph->adjMat[i][j + 1];
        }
    }

View on GitHub (pinned to 69932aed18)

Solutions

  1. Guard with 0 <= index && index < graph->size.
  2. Recompute indices after deletions.
  3. Scan vertices[] to map a value to its current index.

Example fix

// before
removeVertex(graph, 5);   // size == 5

// after
if (graph->size > 0) removeVertex(graph, graph->size - 1);
Defensive patterns

Strategy: validation

Validate before calling

static inline int graphValidIndex(const GraphAdjMat *g, int idx) {
    return g != NULL && idx >= 0 && idx < g->size;
}

if (graphValidIndex(graph, index)) removeVertex(graph, index);

Prevention

When it happens

Trigger: removeVertex(graph, index) with index < 0 or index >= graph->size — typically a stale index after a prior deletion.

Common situations: Stale cached indices; value/index confusion; in-loop deletion with a counter index.

Related errors


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