krahets/hello-algo · error

индексы ребра выходят за границы или совпадают

Error message

индексы ребра выходят за границы или совпадают

What it means

Russian localization of the addEdge guard (see error 602). addEdge rejects negative/out-of-range endpoints and forbids i == j (simple undirected graph, no self-loops). Logged to stderr; adjMat unchanged.

Source

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

    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];
        }
    }
    graph->size--;
}

/* Добавление ребра */
// Параметры i и j соответствуют индексам элементов vertices
void addEdge(GraphAdjMat *graph, int i, int j) {
    if (i < 0 || j < 0 || i >= graph->size || j >= graph->size || i == j) {
        fprintf(stderr, "индексы ребра выходят за границы или совпадают\n");
        return;
    }
    graph->adjMat[i][j] = 1;
    graph->adjMat[j][i] = 1;
}

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

/* Вывести матрицу смежности */

View on GitHub (pinned to 69932aed18)

Solutions

  1. Pass indices, not values.
  2. Insert endpoints first.
  3. Reject i == j at the call site.

Example fix

// before
addEdge(graph, 1, 3);

// after
int i = indexOf(graph, 1), j = indexOf(graph, 3);
if (i >= 0 && j >= 0 && i != j) addEdge(graph, i, j);
Defensive patterns

Strategy: validation

Validate before calling

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

if (graphValidEdge(graph, i, j)) addEdge(graph, i, j);

Prevention

When it happens

Trigger: addEdge(graph, i, j) with i/j out of range or equal — commonly vertex values used as indices, or a self-loop.

Common situations: Value-vs-index confusion; self-loops; edges before endpoints exist.

Related errors


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