我是否以错误的方式使用了 realloc?
Did I use realloc in a wrong way?
这是我程序中与 realloc() 有关的部分。我给数组 myEdge
一个初始大小 my_edge_num
,当这个大小不够时,realloc() more space 给它。但是,即使新的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);
}
您重新分配的字节太少。
应该是
temp_edge = realloc(myEdge, temp_edge_num*sizeof(Edge));//allocate more space
相反。
这是我程序中与 realloc() 有关的部分。我给数组 myEdge
一个初始大小 my_edge_num
,当这个大小不够时,realloc() more space 给它。但是,即使新的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);
}
您重新分配的字节太少。
应该是
temp_edge = realloc(myEdge, temp_edge_num*sizeof(Edge));//allocate more space
相反。