繁体   English   中英

当我尝试分配新内存时,为什么realloc会崩溃我的程序?

[英]why does realloc crash my program when i am trying to allocate new memory?

我的realloc函数有一些问题。 我有结构国家和内部我有结构“城市”,包括指向城市阵列,每个城市有3个fiels:

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);
}

但在删除后,当我尝试重新分配时,我在realloc时遇到此函数的错误

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->其他功能的城市。 哪里可以问题? 谢谢

你不能在指向分配块中间的指针上调用free country->cities指向内存中的连续块( N x sizeof(City) )。 一个好的经验法则是,如果你有malloc(something) ,你必须拥有(并且只能拥有) free(something)地方的free(something)malloc(country->cities) - > free(country->cities) )。

代码崩溃是因为第一次调用freeCity释放freeCity country->cities 也许您希望.cities是一个指针数组,即City** ,在这种情况下,您将分别分配每个City ,然后cities数组将指向您可以单独释放的块。

假设您在另一个函数中分配country->cities

您正在呼叫freeCity(country->cities+i);

但是在freeCity函数中你也可以free(pCity);获得城市free(pCity);

所以,对于cities阵列,你在city[i]上免费拨打电话。 这有两个问题

  1. 对于第一个循环,当i0 ,您释放数组然后重新分配它。
  2. 对于其他迭代,当i非零时,您在错误的位置释放。 您应该释放数组的基础而不是数组内部。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM