krahets/hello-algo · error

圖的頂點數量已達最大值

Error message

圖的頂點數量已達最大值

What it means

Traditional-Chinese (zh-hant) localization of the addVertex capacity check (see error 600). The graph's vertices[] and adjMat[][] are fixed at compile time via #define MAX_SIZE 100; the 101st addVertex logs to stderr and returns void without inserting.

Source

Thrown at zh-hant/codes/c/chapter_graph/graph_adjacency_matrix.c:39

    GraphAdjMat *graph = (GraphAdjMat *)malloc(sizeof(GraphAdjMat));
    graph->size = 0;
    for (int i = 0; i < MAX_SIZE; i++) {
        for (int j = 0; j < MAX_SIZE; j++) {
            graph->adjMat[i][j] = 0;
        }
    }
    return graph;
}

/* 析構函式 */
void delGraphAdjMat(GraphAdjMat *graph) {
    free(graph);
}

/* 新增頂點 */
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 的頂點

View on GitHub (pinned to 69932aed18)

Solutions

  1. Cap input at 100 vertices.
  2. Raise MAX_SIZE and recompile (quadratic memory cost).
  3. Use the adjacency-list implementation for larger graphs.

Example fix

// before
for (int i = 0; i < 1000; i++) addVertex(graph, i);

// after
for (int i = 0; i < 1000 && graph->size < MAX_SIZE; i++) addVertex(graph, i);
Defensive patterns

Strategy: validation

Validate before calling

static inline int graphCanAddVertex(const GraphAdjMat *g) {
    return g != NULL && g->size < MAX_SIZE;
}

if (graphCanAddVertex(graph)) addVertex(graph, val);

Prevention

When it happens

Trigger: addVertex(graph, val) when graph->size == 100.

Common situations: Datasets larger than 100 nodes; stress tests past the cap; assuming dynamic resizing.

Related errors


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