c - 为什么在我尝试分配新内存时 realloc 会使我的程序崩溃?

标签 c function realloc

我的 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 中间的指针上调用 freecountry->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/

相关文章:

ios - 我可以在 swift 中有两种类型的参数吗?

function - 函数的 Modelica 和事件生成

android - 如何知道我正在为使用 ndk-build 构建哪个 API 级别?

c++ - 创建采用可变数量的参数和数据类型的函数

c++ - GLSL 1.2 + 纹理非二的幂

c - 使用 fgetc C 从文件读取字符串时出现问题(不使用 fscanf 等)

c - 移动指针并重新分配,C

c - 输出中的奇怪行为

c++ - C POSIX API 是否与 C++ STL 兼容

c - dtoa-ftoa c语言小数点管理