【发布时间】:2017-10-15 18:11:25
【问题描述】:
我必须根据一些特定的准则制作一个带有函数的图形数据类型。
我必须有一个初始化空图的函数。在这个函数中,我将第一个顶点设置为 NULL。只是测试一下,我运行我的 num_vertices 方法,我得到一个分段错误。它应该返回 0。
在我自己的调试之后,我了解到,在对新图调用 init 函数之后,调用 num_vertices 函数以某种方式传递了一个不为 NULL 的顶点,即使 init 函数将其设置为 NULL。因此,我的 num_vertices 方法会遍历为我的图分配的所有内存,直到遇到 seg 错误。
为什么会发生这种情况,如何将其设置为 NULL 以便我的 num_vertices 工作?
我的图形结构(需要做类似这样):
typedef struct Edge Edge;
typedef struct Vertex Vertex;
typedef struct Graph Graph;
struct Graph {
Vertex *vertex;
};
struct Vertex {
/* use a tree to store vertices */
Vertex *left;
Vertex *right;
char *name;
Edge *edge; /* the edge between this vertex and its root */
};
struct Edge {
unsigned int cost;
};
我的 init_graph() 和 num_vertices():
void init_graph(Graph *graph) {
graph = (Graph *)malloc(sizeof(Graph));
graph->vertex = NULL;
}
int num_vertices(Graph graph) {
return count_vertices(graph.vertex);
}
int count_vertices(Vertex *vertex) {
int count = 0;
if (vertex != NULL) {
count += count_vertices(vertex->left);
count++;
count += count_vertices(vertex->right);
}
return count;
}
最后,我用来测试的代码出现了段错误:
int main() {
Graph graph;
init_graph(&graph); /* initialize new graph */
assert(num_vertices(graph) == 0); /* seg fault here */
printf("It all worked!\n");
return 0;
}
【问题讨论】:
-
你为什么要首先分配内存给
graph->vertex然后然后用NULL覆盖那个set指针?! -
(Graph** graph) and *graph = malloc(...)或者,返回一个图表* -
这些片段如何编译?
int num_vertices(Graph graph)应该是int num_vertices(struct Graph graph)。请发布显示问题的Minimal, Complete, and Verifiable example。 -
@WeatherVane
malloc中的演员表 - 我怀疑这是 C++.. -
它用 C++ 编译 :))
标签: c struct segmentation-fault