Pergunta

I am attempting to handle various structures and pointers in C, and I am particularly stumped by uninitialized values even after calloc-ing the arrays using a function calling by reference

some code (The List successfully works without 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 }   

the error report

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

Is there any strategy that I can successfully initialize values while calling by reference?

Foi útil?

Solução

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

at initializeGraph use i <= (*G)->size; but set tmp->size = n; after call initializeGraph

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top