小编The*_*ter的帖子

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

我已经读过使用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} …
Run Code Online (Sandbox Code Playgroud)

c struct pointers

1
推荐指数
1
解决办法
90
查看次数

标签 统计

c ×1

pointers ×1

struct ×1