2017-10-15 67 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對象分配了內存!閱讀有關變量和指針的信息。 –