I am writing a lab, an error occurs when re-allocating memory:
a.out: realloc(): invalid old size: 0x089d4008
The code where memory is allocated is:
graph = (vertex*) malloc(sizeof(vertex)*(N+1)); res = (int*) malloc(sizeof(int)*N); for(int i = 1; i <= N; i++) { graph[i].color = 0; graph[i].num_edges = 0; graph[i].max_edges = 5; graph[i].edges = (edge*) malloc(sizeof(edge)*graph[i].max_edges); graph[i].value = i; } for(int i = 0; i < M; i++) { int temp1, temp2; scanf("%d %d", &temp2, &temp1); if(graph[temp1].num_edges >= graph[temp1].max_edges) { graph[temp1].max_edges *= 2; graph[temp1].edges = (edge*) realloc(graph[temp1].edges, graph[temp1].max_edges); } graph[temp1].num_edges += 1; graph[temp1].edges[graph[temp1].num_edges - 1].to = graph+temp2; }
What a mistake, I do not understand.