krahets/hello-algo · warning

图的顶点数量已达最大值

Error message

图的顶点数量已达最大值

What it means

Printed to stderr by addVertex in the GraphAdjMat teaching class (an adjacency-matrix undirected graph) when graph->size == MAX_SIZE (100). Unlike the Ruby implementations which raise exceptions, this C function merely prints the message and returns silently — it does NOT set errno, return an error code, or abort. The vertex is silently not added, so the caller has no programmatic way to detect the failure except by checking preconditions beforehand.

Source

Thrown at 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. Check graph->size < MAX_SIZE before calling addVertex.
  2. Increase the MAX_SIZE #define at the top of the file (or in common.h) and recompile if your dataset requires more vertices.
  3. Call removeVertex to free a slot before adding a new vertex when at capacity.
  4. Redirect stderr to a log file and scan for this message during testing.

Example fix

// before
addVertex(graph, val);  // silently fails if size == 100

// after
if (graph->size < MAX_SIZE) {
    addVertex(graph, val);
} else {
    // handle capacity exhaustion: resize MAX_SIZE or remove a vertex
}
Defensive patterns

Strategy: validation

Validate before calling

if (graph->size < MAX_SIZE) {
    addVertex(graph, val);
}

Type guard

/* C: precondition check before addVertex */
static inline bool can_add_vertex(const GraphAdjMat *g) {
    return g->size < MAX_SIZE;
}

Prevention

When it happens

Trigger: Calling addVertex when the graph already contains exactly MAX_SIZE (100) vertices. This happens after 100 successful addVertex calls without any removeVertex calls, or if MAX_SIZE was lowered.

Common situations: Loading a graph dataset with more than 100 nodes; forgetting that MAX_SIZE is a compile-time #define (100); not calling removeVertex to free slots; increasing graph density without increasing MAX_SIZE.

Related errors


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