char *在结构中不是免费的()由cleanUp函数

时间:2015-09-15 16:17:18

标签: c pointers struct

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

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);

它标记了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 

如果我在功能结束时释放它们,那么:

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 个答案:

答案 0 :(得分:5)

您的AddNewAccount函数永远不会增加e->numAccounts,因此CleanUp总是表现为Collection不包含任何帐户,所以什么也不做。