简体   繁体   中英

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

i have some issue with my realloc function. i have the struct Country and inside i have struct "City" wich include point to cities array that every city is have 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;

i need to delete city from the cities array so i free the city with function that i built called freeCity:

void freeCity(City *pCity)
{
    free(pCity->name);
    free(pCity->popluarFood);
    free(pCity);
}

but after delelte when i am trying to realloc i get error in this function when 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;
}

i malloc country->cities in other function. where can be the problem? thank you

You cannot call free on a pointer to the middle of an allocated chunk. country->cities points to a contiguous block in memory ( N x sizeof(City) ). A good rule of thumb is, if you have malloc(something) , you must have (and can only have) free(something) somewhere else ( malloc(country->cities) -> free(country->cities) ).

The code crashes because the first call to freeCity frees country->cities . Perhaps you want .cities to be an array of pointers, ie City** , in that case you would allocate each City separately, and the cities array would then point to chunks which you can free individually.

Assuming that you allocate country->cities in another function.

You are calling freeCity(country->cities+i);

But in the freeCity function you are also freeing the city free(pCity);

So, for the cities array, you are calling free on city[i] . This has two issues

  1. For the first loop, when i is 0 , you are freeing the array and then reallocating it.
  2. For the other iterations, when i is non zero, you are freeing at the wrong place. You should free the base of the array and not inside the array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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