如标题所述,我遇到了错误
访问冲突读取位置0xCDCDCDCD。
现在,我正在处理一系列链接列表,并且我认为麻烦在于围绕添加到链接列表中。我通常对此表示满意,但我觉得我在内存分配上做错了什么。
这是我的结构:
图形:
typedef struct graph
{
int V;
int *state;
EdgeList *edges;
} Graph;
边缘:
typedef struct edge
{
int toVertex;
int weight;
} Edge;
边列表:
typedef struct edgeNode
{
Edge edge;
struct edgeNode *next;
} *EdgeList;
这是运行所有功能的主要功能:
main()
{
Graph myGraph;
scanf("%d", &(myGraph.V));
myGraph.state = (int)malloc(myGraph.V*sizeof(int));
myGraph.edges = (EdgeList*)malloc(myGraph.V*sizeof(EdgeList));
int *inDegrees;
inDegrees = (int)malloc(sizeof(int)*myGraph.V);
/* Sets all array values to 0 */
for (int counter = 0; counter < myGraph.V; counter++)
{
inDegrees[counter] = 0;
}
for (int i = 0; i < myGraph.V; i++)
{
int number_of_edges;
int input = 0; /*For that little experimental bit*/
scanf("%d", &(myGraph.state[i]));
scanf("%d", &number_of_edges);
if (number_of_edges > 0)
{
for (int j = 0; j < number_of_edges; j++)
{
Edge newEdge;
scanf("%d,%d", &(newEdge.toVertex), &(newEdge.weight));
inDegrees[newEdge.toVertex]++;
printf("%s%d\n", "\nOoh, new input for ", newEdge.toVertex);
/*insert at front*/
EdgeList newNode = (EdgeList)malloc(sizeof (struct edgeNode));
newNode->edge = newEdge;
newNode->next = myGraph.edges[i];
myGraph.edges[i] = newNode;
/* Bit to calculate state.*/
EdgeList current = myGraph.edges[i];
while (current != NULL)
{
if (current->edge.toVertex == i)
{
input += (current->edge.weight)*(myGraph.state[i]);
}
current = current->next;
}
}
if (input > 0)
{
myGraph.state[i] = 1;
}
else
{
myGraph.state[i] = 0;
}
}
}
//print
for (int k = 0; k < myGraph.V; k++)
{
printf("\n%s%d%s", "In degrees for ", k, ": ");
printf("%d", inDegrees[k]);
}
}
特别是,在遍历链接列表时会出现错误。在上面的代码中,但在这里我将重点介绍:
EdgeList current = myGraph.edges[i];
while (current != NULL)
{
if (current->edge.toVertex == i)
{
input += (current->edge.weight)*(myGraph.state[i]);
}
current = current->next;
}
如果有人可以提供帮助,将不胜感激,因为我很执着。
malloc()
分配的未初始化缓冲区中的值分配给newNode->edge
in newNode->next = myGraph.edges[i];
。newNode
设置为current
viamyGraph.edges[i] = newNode;
和EdgeList current = myGraph.edges[i];
。malloc()
成功current
不在NULL
这里,那么它就进入了循环。current
in current = current->next;
。malloc()
,并在未初始化current != NULL
。要解决此错误,请使用myGraph.edges
以下方式进行初始化:
myGraph.edges = (EdgeList*)malloc(myGraph.V*sizeof(EdgeList));
for (int i = 0; i < myGraph.V; i++)
{
myGraph.edges[i] = NULL;
}
此外,请删除int
从返回的指针的有害强制类型转换malloc()
。显式地将返回值强制转换为指针也被认为是不好的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句