Did I use realloc in a wrong way?

This is a part of my program which is related to realloc(). I give the array myEdge an initial size my_edge_num, when this size is not enough, realloc() more space to it. However, even though the new realloc temp_edge is not NULL, it still says EXC_BAD_ACCESS in the next step when it reaches the location in the array which beyonds old size but less than new size.

string_first = strtok_r(buffer, " tn", &save_ptr);
int i=0;

int temp_edge_num;
Edge *temp_edge;
while (string_first != NULL)
    temp_first = atoi(string_first);

    string_second = strtok_r(NULL," tn",&save_ptr);

    temp_second = atoi(string_second);

    if(i>=my_edge_num)// if it finds that it reaches original size
        temp_edge_num = i + EDGE_NUM_ADJUST;//add more size

        temp_edge = (Edge *)realloc(myEdge, temp_edge_num);//allocate more space
        if(temp_edge)// if allocate more space successfully 
            myEdge = temp_edge;// let original = new one
        my_edge_num = temp_edge_num;


        myEdge[i].first=temp_first; //it says EXC_BAD_ACCESS here


    string_first = strtok_r(NULL, " tn", &save_ptr);


Source: linux

Leave a Reply