Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading