如标题所述,我遇到了一个错误
Access violation reading location 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;
}
如果有人能提供帮助,我将不胜感激,因为我被困住了。
最佳答案
- 在
newNode->next = myGraph.edges[i] 中将通过
。malloc()
分配的未初始化缓冲区中的值分配给newNode->edge
; newNode
通过myGraph.edges[i] = newNode;
和EdgeList current = myGraph.edges 设置为
.current
[i];- 假设
malloc()
成功,current
在这里不为NULL
,因此进入循环。 - 在
current = current->next;
中将1中赋值的未初始化值赋值给current
。 - 通过使用通过
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;
}
此外,删除对从 malloc()
返回的指针的 int
的有害转换。将返回值显式转换为指针也是 not considered as good .
关于c - 访问冲突读取位置 0xCDCDCDCD,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36950405/