krahets/hello-algo · error

頂點索引越界

Error message

頂點索引越界

What it means

Traditional-Chinese localization of the removeVertex bounds check (see error 601). Vertices are positional; an index outside [0, graph->size) is rejected with an stderr message and a void return carrying no status.

Source

Thrown at zh-hant/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 each deletion.
  3. Look up the index from vertices[] when you only have the value.

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 — usually a stale index after an earlier deletion.

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

Related errors


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