这是我的程序的一部分,它与realloc()有关。我给数组myEdge
一个初始大小my_edge_num
,当这个大小不够时,realloc()会有更多的空间。但是,即使新的realloc temp_edge
不是NULL,当它到达数组中超出旧大小但小于新大小的位置时,仍会在下一步中显示EXC_BAD_ACCESS
。
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);
}
答案 0 :(得分:3)
您重新分配的字节太少了。
应该是
temp_edge = realloc(myEdge, temp_edge_num*sizeof(Edge));//allocate more space
代替。