Reputation: 241
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?
Upvotes: 1
Views: 117
Reputation: 40623
Your AddNewAccount
function never increments e->numAccounts
, and so CleanUp
always acts as though the Collection
contains no accounts, and so does nothing.
Upvotes: 5