krahets/hello-algo · error

頂点インデックスが範囲外です

Error message

頂点インデックスが範囲外です

What it means

Japanese localization of the removeVertex bounds check (see error 601). The graph indexes vertices by position in a contiguous array, so an index outside [0, graph->size) is rejected. The function logs to stderr and returns void with no status code.

Source

Thrown at ja/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 行目と n 列目を 0 にする
    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. Verify 0 <= index && index < graph->size before the call.
  2. Recompute cached indices after each deletion (higher indices shift down).
  3. Look up the index by scanning vertices[] when you only have the value.

Example fix

// before
removeVertex(graph, 5);   // size == 5 -> out of bounds

// 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 — e.g. a stale index used after a prior deletion shifted vertices left.

Common situations: Cached indices going stale across mutations; confusing a vertex value with its array index; deleting inside a loop with a counter used as index.

Related errors


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