0

我试图在 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)

是否有任何策略可以在通过引用调用时成功初始化值?

4

1 回答 1

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

在 initializeGraph 使用i <= (*G)->size;tmp->size = n;在调用 initializeGraph 后设置

于 2013-07-28T21:52:54.173 回答