0

我試圖處理各種結構和指針在C,和我特別 未初始化的值甚至後難倒訪問釋放calloc-ING通過參考使用函數調用陣列Valgrind的C:通過參考與未初始化值

一些代碼(列表成功作品,未經圖表):

// Graph 
43 void initializeGraph (Graph *G){ 
44 if (G == NULL || *G == NULL){ 
45  fprintf (stderr, "Graph failed to initialize. Exit\n"); 
46  exit(EXIT_FAILURE); 
47 } 
48 // We will leave 0th index as dummy data 
49 // for math-based purposes 
50 for (int i = 0; i <= (*G)->size; ++i){ 
51  (*G)->adj_list[i] = newList(); 
52  (*G)->color[i] = 'w'; 
53  (*G)->parent[i] = NIL; 
54  (*G)->distance[i] = INF; 
55 } 
56 } 
57 
58 Graph newGraph(int n){ 
59 // Some printing debug 
60 printf("Size of List: %lu\n", sizeof(List)); 
61 printf("Size of Graph_obj: %lu\n", sizeof(Graph_obj)); 
62 
63 Graph tmp = malloc(sizeof(Graph_obj)); 
64 tmp->adj_list = NULL; 
65 tmp->color = NULL; 
66 tmp->parent = NULL; 
67 tmp->distance = NULL; 
68 tmp->adj_list = calloc (n+1, sizeof (List)); 
69 tmp->color = calloc (n+1, sizeof (char)); 
70 tmp->parent = calloc (n+1, sizeof (int)); 
71 tmp->distance = calloc (n+1, sizeof (int)); 
72 initializeGraph (&tmp); 
73 tmp->size = n; tmp->order = n; tmp->src = NIL; 
74 return tmp; 
75 } 

錯誤報告

// This one caused a segfault 
==7293== 1 errors in context 1 of 2: 
==7293== Invalid read of size 4 
==7293== at 0x401000: length (List.c:83) 
==7293== by 0x400D8F: addArc (Graph.c:139) 
==7293== by 0x4007E5: main (GraphClient.c:38) 
==7293== Address 0x1c is not stack'd, malloc'd or (recently) free'd 

// This one is the undefined value that led to segfault 
==7293== 2 errors in context 2 of 2: 
==7293== Conditional jump or move depends on uninitialised value(s) 
==7293== at 0x4009B5: initializeGraph (Graph.c:50) 
==7293== by 0x400A88: newGraph (Graph.c:68) 
==7293== by 0x4007CB: main (GraphClient.c:37) 
==7293== Uninitialised value was created by a heap allocation 
==7293== at 0x4A05FDE: malloc (vg_replace_malloc.c:236) 
==7293== by 0x400A05: newGraph (Graph.c:63) 
==7293== by 0x4007CB: main (GraphClient.c:37) 

有沒有小號Trategy,我可以成功地初始化值,而通過引用調用?

回答

2
72 initializeGraph (&tmp); 
73 tmp->size = n; tmp->order = n; tmp->src = NIL; 

在initializeGraph使用i <= (*G)->size;但通話initializeGraph後置tmp->size = n;

+0

喔...謝謝你指出來,因爲我應該調用next函數,它的工作的其餘部分之前初始化大小。 – JBRPG