gpt4 book ai didi

c - Valgrind C : Accessing by reference and unitialized value

转载 作者:太空宇宙 更新时间:2023-11-04 08:54:37 24 4
gpt4 key购买 nike

我正在尝试处理 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)

有什么策略可以在通过引用调用时成功初始化值吗?

最佳答案

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

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

关于c - Valgrind C : Accessing by reference and unitialized value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17913202/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com