char*in structs不是free()'由cleanUp函数

The*_*ter 1 c struct pointers

我已经读过使用malloc()时的规则总是匹配free().如果在程序中使用malloc()7次,则必须有相应数量的free()s.但是,这似乎不适用于几个char*我在一个结构中的malloc.结构:

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

typedef struct
{
    unsigned int numAccounts;
    ppAccount accounts;
}Collection,*pAccountCollection;
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

最后,最后调用清理:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在检查泄漏

    _CrtDumpMemoryLeaks();
    _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF|_CRTDBG_LEAK_CHECK_DF);
Run Code Online (Sandbox Code Playgroud)

并且它标记了newAct的ID和PassWord,因为没有释放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 
Run Code Online (Sandbox Code Playgroud)

如果我在功能结束时释放它们,就像这样:

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);
}
Run Code Online (Sandbox Code Playgroud)

我在AccountCollection帐户集合中丢失了对该帐户的引用.

任何见解?

Man*_*rse 5

你的AddNewAccount功能永远不会增加e->numAccounts,因此CleanUp总是表现得好像不Collection包含任何帐户,所以什么都不做.