简体   繁体   English

未能释放 c 中的动态结构数组

[英]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:当我结束程序并想使用以下代码释放 AirportManager 时:

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?我已经调试了这个,所有参数都很好,但是在循环中运行一次后程序退出,我应该在免费的 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 .你只需要释放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对于尺寸,使用size_t类型而不是int

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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