C语言实现图顶点添加功能失败求助
图顶点添加C程序运行失败问题排查
我看了你贴的代码片段,能发现几个明显的问题导致程序运行失败,咱们一步步来梳理:
1. 致命的栈溢出问题
你定义的Graph结构体里,vertices数组用了INT_MAX作为长度:
typedef struct MyGraph{ VNode vertices[INT_MAX]; }Graph;
INT_MAX通常是2147483647,这么大的数组直接声明在结构体里,不管是栈上分配还是堆上分配都会直接爆内存——栈空间本来就很小(一般几MB),根本装不下这么多元素,这大概率是程序崩溃的首要原因。
2. 字符串处理的野指针风险
在make_node函数里,你直接把传入的first指针赋值给vertices[i].data:
G.vertices[i++].data = first;
如果first是临时字符串或者栈上的字符串,后续可能会被释放或覆盖,导致data变成野指针,访问时触发未定义行为。
3. 未完成的初始化逻辑
从你贴的代码片段看,make_node的循环没写完,而且只给i=1的顶点初始化了firstarc,i=0的顶点firstarc没设为NULL,这会导致后续操作边的时候出现随机指针错误。
修复后的代码示例
我给你调整一下核心部分的代码,解决这些问题:
#include <stdio.h> #include <ctype.h> #include <stdlib.h> #include <string.h> #include <limits.h> typedef struct EdgeNode{ int adjvex; struct EdgeNode *nextarc; }ENode, *PENode; typedef struct VertexNode{ char *data; ENode *firstarc; }VNode; // 改成动态数组+顶点计数,避免栈溢出 typedef struct MyGraph{ VNode *vertices; int vertex_count; int max_vertices; // 可选:记录数组的最大容量,方便扩容 }Graph; // 初始化图的函数 void init_graph(Graph *G, int initial_size) { if (initial_size <= 0) initial_size = 10; // 默认初始容量 G->vertices = malloc(sizeof(VNode) * initial_size); if (!G->vertices) { perror("malloc failed"); exit(EXIT_FAILURE); } G->vertex_count = 0; G->max_vertices = initial_size; } // 添加顶点的函数 int add_vertex(Graph *G, char *vertex_data) { // 检查是否需要扩容 if (G->vertex_count >= G->max_vertices) { int new_size = G->max_vertices * 2; VNode *new_vertices = realloc(G->vertices, sizeof(VNode)*new_size); if (!new_vertices) { perror("realloc failed"); return -1; } G->vertices = new_vertices; G->max_vertices = new_size; } // 分配内存并拷贝顶点数据 G->vertices[G->vertex_count].data = malloc(strlen(vertex_data)+1); if (!G->vertices[G->vertex_count].data) { perror("malloc data failed"); return -1; } strcpy(G->vertices[G->vertex_count].data, vertex_data); // 初始化边链表头为NULL G->vertices[G->vertex_count].firstarc = NULL; G->vertex_count++; return G->vertex_count - 1; // 返回顶点索引 } // 释放图的内存 void free_graph(Graph *G) { for (int i=0; i<G->vertex_count; i++) { free(G->vertices[i].data); // 还要释放边节点,这里省略,你可以自己补充 ENode *p = G->vertices[i].firstarc; while (p) { ENode *temp = p; p = p->nextarc; free(temp); } } free(G->vertices); G->vertices = NULL; G->vertex_count = 0; G->max_vertices = 0; } // 测试用例 int main() { Graph G; init_graph(&G, 5); add_vertex(&G, "A"); add_vertex(&G, "B"); add_vertex(&G, "C"); printf("Added %d vertices:\n", G.vertex_count); for (int i=0; i<G.vertex_count; i++) { printf("Vertex %d: %s\n", i, G.vertices[i].data); } free_graph(&G); return 0; }
关键修复点说明
- 把静态数组改成动态分配的数组,避免栈溢出,还支持动态扩容
- 给顶点的
data单独分配内存并拷贝字符串,避免野指针 - 完善了图的初始化和内存释放逻辑,防止内存泄漏
- 添加顶点时确保每个顶点的
firstarc都初始化为NULL
你可以基于这个版本调试,应该能解决运行失败的问题。如果还有其他报错,比如边操作的问题,可以再贴出完整代码进一步排查。
内容的提问来源于stack exchange,提问作者Amir Bashir
相关产品推荐
相关产品推荐

