Valgrind C:通过引用和未初始化的值访问

时间:2013-07-28 21:43:32

标签: c segmentation-fault pass-by-reference initialization calloc

我试图处理C中的各种结构和指针,我特别难过 即使在使用通过引用调用的函数调用数组之后,未初始化的值

一些代码(List没有Graph成功运行):

// 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)

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

1 个答案:

答案 0 :(得分:2)

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

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