简体   繁体   中英

char* in structs not being free()'d by cleanUp function

I've read that the rule when using malloc() is to always have a matching free(). If malloc() is used 7 times in a program, there must be a corresponding number of free()s. However, this does not seem to be working for several char* I've malloc'd inside of a struct. The struct:

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

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

The mallocs (function simplified):

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

And finally, the cleanup called at the end:

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

I'm checking for leaks with

    _CrtDumpMemoryLeaks();
    _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF|_CRTDBG_LEAK_CHECK_DF);

And it's flagging the ID and PassWord of newAct as 26 bytes not being freed.

 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 

If I free them at the end of the fuction like so:

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

I lose the reference to that account in the collection of accounts AccountCollection e.

Any insight?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM