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.



    2 answers 2

    Perhaps because in the first cycle you use iteration with 1 instead of 0. temp1 what value does it take?

    • one
      The input values ​​temp1 and temp2 should be checked to ensure that they refer to the already initialized elements of the graph array. You have zero and Nth elements are not initialized in the first cycle, garbage in them. If you enter 0 in temp1, this explains everything. - avp
    • The case was not specifically in this place, but close. Many thanks for the reply - saigono

    And malloc correctly worked? There is nothing realloc if malloc did not work correctly.