我是否以错误的方式使用realloc?
这是我的程序的一部分,与realloc()相关。我给数组我是否以错误的方式使用realloc?,c,linux,memory,realloc,C,Linux,Memory,Realloc,这是我的程序的一部分,与realloc()相关。我给数组myEdge一个初始大小myu edge\u num,当这个大小不够时,realloc()会给它更多的空间。但是,即使新的realloctemp_edge不为空,但在下一步到达数组中超出旧大小但小于新大小的位置时,它仍会显示EXC_BAD_ACCESS string_first = strtok_r(buffer, " \t\n", &save_ptr); int i=0; int temp_edge_num; Edge *tem
myEdge
一个初始大小myu edge\u num
,当这个大小不够时,realloc()会给它更多的空间。但是,即使新的realloctemp_edge
不为空,但在下一步到达数组中超出旧大小但小于新大小的位置时,它仍会显示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”……如果realloc失败,那么您可以假装有足够的空间,而实际上您没有看到这一行:'string_second=strtok_r(NULL,\t\n,&save_ptr);'在使用strtok()之前,请始终检查它返回的值。如果对strtok()的调用返回NULL,那么这一行:'temp_second=atoi(string_second);'将导致seg故障event@ammoQ对你