我的 realloc 函数有一些问题。 我有结构国家,里面有结构“城市”,其中包括指向城市数组的点,每个城市都有 3 个字段:
typedef struct Country {
char *name;
int numberOfCities;
City* cities;
cordinate cordinateOfCountryLeft;
cordinate cordinateOfCountryRight;
}Country;
typedef struct City
{
char *name;
char * popluarFood;
int numberOfPeople;
}City;
我需要从城市数组中删除城市,这样我就可以使用我构建的名为 freeCity 的函数释放城市:
void freeCity(City *pCity)
{
free(pCity->name);
free(pCity->popluarFood);
free(pCity);
}
但是当我尝试重新分配时删除后我在重新分配时在这个函数中出错
status freeCityFromCountry(Country *country, char *cityName)
{
for (int i = 0; i < country->numberOfCities; i++) {//for
if (strcmp(country->cities[i].name, cityName)==0)
{
freeCity(country->cities+i);
country->cities[i] = country->cities[country->numberOfCities - 1];
// free(country->cities[country->numberOfCities - 1]);
country->cities = (City*)realloc(country->cities,(country->numberOfCities-1));
country->numberOfCities--;
return success;
}
}//for
return failure;
}
我在其他函数中 malloc country->cities。 问题出在哪里?
最佳答案
您不能在指向已分配 block 中间的指针上调用 free
。 country->cities
指向内存中的一个连续 block (N x sizeof(City)
)。一个好的经验法则是,如果你有 malloc(something)
,你必须在某处有(并且只能有)free(something)
else (malloc(country->cities)
-> free(country->cities)
).
代码崩溃是因为第一次调用 freeCity
释放了 country->cities
。也许您希望 .cities
是一个指针数组,即 City**
,在这种情况下,您将分别分配每个 City
,并且cities
数组将指向您可以单独释放的 block 。
关于c - 为什么在我尝试分配新内存时 realloc 会使我的程序崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53315787/