2015-09-15 37 views
1

我讀過使用malloc()時的規則是始終有一個匹配的free()。如果在程序中使用malloc()7次,則必須有相應數量的free()。然而,這似乎不適用於幾個char *我malloc'd結構內。該結構:char * in structs not being free()'d by cleanUp function

typedef struct 
{ 
    char* ID; 
    char* PassWord; 
}Account, *pAccount, **ppAccount; 

typedef struct 
{ 
    unsigned int numAccounts; 
    ppAccount accounts; 
}Collection,*pAccountCollection; 

的mallocs(功能簡化):

void AddNewAccount(pAccountCollection e){ 
    int string_length = sizeof(char)*26; 
    pAccount newAct = malloc(sizeof(Account)); 

    newAct->ID = malloc(string_length); 
    newAct->PassWord = malloc(string_length); 
    e ->numAccounts++; 

    e->accounts[e->numAccounts-1] = newAct; 
} 

最後,稱爲末的清理:

void CleanUp(pAccountCollection e){ 
unsigned int i; 

    if(e->numAccounts != 0){ 
     for (i = 0; i < e->numAccounts; i++){ 
      free(e->accounts[i]->ID); 
      free(e->accounts[i]->PassWord); 
      free(e->accounts[i]); 
     } 
     free(e->accounts); 
    } 
} 

我與

檢查泄漏
_CrtDumpMemoryLeaks(); 
    _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF|_CRTDBG_LEAK_CHECK_DF); 

它是fla將newAct的標識和密碼加密爲26個字節未被釋放。

Detected memory leaks! 
Dumping objects -> 
{73} normal block at 0x006F9268, 26 bytes long. 
    Data: <    > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD 
{72} normal block at 0x006F45E8, 26 bytes long. 
    Data: <    > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD 

如果我在機能的研究中,像這樣的結束讓他們自由:

void AddNewAccount(pAccountCollection e){ 
    int string_length = sizeof(char)*26; 
    pAccount newAct = malloc(sizeof(Account)); 

    newAct->ID = malloc(string_length); 
    newAct->PassWord = malloc(string_length); 

    e->accounts[e->numAccounts-1] = newAct; 
    free(newAct->ID); 
    free(newAct->PassWord); 
} 

我失去帳戶AccountCollection e的集合中的引用到該帳戶。

任何見解?

+1

提示:您可以省略'CleanUp'-Function中的條件'e-> numAccounts!= 0',因爲在這種情況下for循環將被忽略('0 <0'總是爲false ... )。 – junix

+1

正如一邊說:'sizeof(char)'總是按照定義1 - sizeof的單位是char。 –

+0

不要'typedef'指針!這混淆了語義,很難閱讀和維護。只有'typedef'基本類型並明確使用'*'。 – Olaf

回答

5

AddNewAccount函數從不遞增e->numAccounts,所以CleanUp總是充當雖然Collection不含賬戶,所以什麼都不做。

+1

我在編寫代碼的時候太簡化了代碼。 numAccounts ++在代碼中。 Editted。 – TheFaster