将struct变量初始化为NULL,但在调用时不为null

时间:2017-10-15 18:11:25

标签: c struct segmentation-fault

我必须根据一些特定的指导原则制作带有函数的图数据类型。

我必须有一个初始化空图的函数。在这个函数中,我将第一个顶点设置为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;
}

最后,我用来测试这个代码得到一个seg错误的代码:

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;
}

1 个答案:

答案 0 :(得分:0)

您将Graph的地址分配给一个函数,该函数通过一个指针来操作它,在该指针中存储动态分配的内存块,因此您不会在原始变量中查找任何内容。这是无稽之谈。只需初始化结构,如下所示:

void init_graph(Graph *graph) {
    graph->vertex = (Vertex *)malloc(sizeof(Vertex));
    graph->vertex = NULL;
}

请注意,除非您输入定义的图表,否则您的代码无效C.