简体   繁体   中英

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?

    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

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