Search code examples
cstructdynamicfreeallocation

failing freeing dynamic struct array in c


I'm having some problem with freeing dynamic struct array and I can't understand why.

first of all there is this struct:

typedef struct
{
    char name[LEN];
    char address[MAX];         
} Airport;

And the constructor I made for this struct isn't using allocation for this struct building.

sec of all there is this struct:

    typedef struct
    {
        Airport* airports;
        int maxAPS;
        int currentAPS;
    } AirportManager;
//constructor
    void addAirport(AirportManager* pAirportManager)
    {
        if (pAirportManager->maxAPS == pAirportManager->currentAPS)
        {
            pAirportManager->maxAPS++;
            pAirportManager->airports = (Airport*)realloc(pAirportManager->airports, sizeof(Airport)*pAirportManager->maxAPS);
            //pAirportManager->airports[pAirportManager->currentAPS] = *(Airport*)malloc(sizeof(Airport)); 
        }....

and when I'm ending my program and want to free the AirportManager with the following code:

void freeAirportManager(AirportManager* pAirportManager)
{
    for (int i = 0; i < pAirportManager->currentAPS; i++)
        free(&pAirportManager->airports[i]);
    free(pAirportManager->airports);
}

I've debuged this one and all the parameters are just fine but after one run in the loop the program exits, what should I change in the free function ?

do I need the marked line in the constructor ? I just added this on thinking it might help, but seems to not work as well... do I need to free only the array itself ?


Solution

  •     for (int i = 0; i < pAirportManager->currentAPS; i++)
            free(&pAirportManager->airports[i]);
    

    You need only to free pAirportManager->airports. You do not have pointer to pointer here.

    So instead of those two lines:

    free(pAirportManager->airports);
    

    I would use flexible array member instead of pointer.

    typedef struct
    {
        char name[LEN];
        char address[MAX];         
    } Airport;
    
    typedef struct
    {
        size_t maxAPS;
        size_t currentAPS;
        Airport airports[];
    } AirportManager;
    

    For sizes use size_t type instead of int