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, " \t\n", &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," \t\n",&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;
}
if((p_id[temp_first]==partitionID)||(p_id[temp_second]==partitionID))
{
myEdge[i].first=temp_first; //it says EXC_BAD_ACCESS here
myEdge[i].second=temp_second;
}
i++;
string_first = strtok_r(NULL, " \t\n", &save_ptr);
}
You reallocate too few bytes.
It should be
temp_edge = realloc(myEdge, temp_edge_num*sizeof(Edge));//allocate more space
instead.