[英]failing freeing dynamic struct array in c
我在釋放動態結構數組時遇到了一些問題,我不明白為什么。
首先有這個結構:
typedef struct
{
char name[LEN];
char address[MAX];
} Airport;
我為這個結構創建的構造函數沒有使用這個結構構建的分配。
首先有這個結構:
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));
}....
當我結束程序並想使用以下代碼釋放 AirportManager 時:
void freeAirportManager(AirportManager* pAirportManager)
{
for (int i = 0; i < pAirportManager->currentAPS; i++)
free(&pAirportManager->airports[i]);
free(pAirportManager->airports);
}
我已經調試了這個,所有參數都很好,但是在循環中運行一次后程序退出,我應該在免費的 function 中更改什么?
我需要構造函數中的標記線嗎? 我剛剛添加了這個,認為它可能會有所幫助,但似乎也不起作用......我是否只需要釋放數組本身?
for (int i = 0; i < pAirportManager->currentAPS; i++)
free(&pAirportManager->airports[i]);
你只需要釋放pAirportManager->airports
。 您在這里沒有指向指針的指針。
所以代替這兩行:
free(pAirportManager->airports);
我會使用靈活的數組成員而不是指針。
typedef struct
{
char name[LEN];
char address[MAX];
} Airport;
typedef struct
{
size_t maxAPS;
size_t currentAPS;
Airport airports[];
} AirportManager;
對於尺寸,使用size_t
類型而不是int
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.