2017-10-15 65 views
-1

我必须根据某些特定的指导原则制作带有函数的图数据类型。初始化一个结构变量为NULL,但调用时它不为null

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

你为什么先*分配内存到'graph-> vertex'然后**然后**用'NULL'覆盖那个设置指针?! –

+2

'(Graph ** graph)和* graph = malloc(...)'或者返回一个Graph * –

+1

这些片段如何编译? 'int num_vertices(Graph graph)'应该是'int num_vertices(struct Graph graph)'。请发布显示问题的[Minimal,Complete和Verifiable示例](http://stackoverflow.com/help/mcve)。 –

回答

0

您分配一个Graph通过其地址的功能whic h通过一个存储动态分配的内存块的指针操作它,因此你不会在原始变量中查找任何东西。这是无稽之谈。只是初始化结构,像这样:

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

请注意,你的代码是不是有效的C除非你的typedef版图形。

+0

非常感谢,这固定了!我是在假设我必须为Graph结构本身以及其内部组件动态分配内存。为什么不是这种情况?此外,结构是typedef-ed我只是从我的OP中省略;我已经添加了它。 – shplaz

+0

这只是一个内存泄漏。 –

+0

@shplaz不是这样,因为编写'Graph graph'已经为Graph对象分配了内存!阅读有关变量和指针的信息。 –