Dynamic memory - destructor causing weird issue

So I'm writing an ATM/Bank program using pointers and dynamic memory. Everytime an account is read in, it is allocated with new.

the problem is I'm using a destructor to at the end to delete the entire array as well as any existing accounts. This is giving me issues like crashing and somehow causing my program to print gibberish strings that were read in from a file. If I comment out the destructor I don't get any crash upon quitting and the program doesnt print gibberish. Is this destructor necessary? if it is, how can I fix it? Code below:

Bank.h destructor
1
2
3
4
5
6
7
8
9
 ~Bank()
{
    while(NumAcctsTotal > 0)
    {
        NumAcctsTotal--;
        delete account[NumAcctsTotal];
        account[NumAcctsTotal] = nullptr;
    }
}


bank.cpp create and delete account
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
void Bank::createAccount(bool Status, string Type, string Num, double Bal,
                         int NumTransacs, Depositor Depstr)
{
   if(NumAcctsTotal < MAX_ACCTS)
   {
      account[NumAcctsTotal] = new Account(Status, Type, Num, Bal, NumTransacs,
                                           Depstr);
      NumAcctsTotal++;
   }
}

bool Bank::deleteAccount(int Index)
{
   if(account[Index] -> getAcctBal() > 0)
      return(true);
   else
      for(int i = Index; i < NumAcctsTotal; i++)
         account[i] = account[i+1];
   NumAcctsTotal--;

   delete account[Index];
   account[Index] = 0;

   return(false);
}

Last edited on
It seems Bank::deleteAccount() is deleting wrong account.
The logic seems to be taking out account at index and then delete it, but in fact you deleting account at index + 1, and leaving it in the array.
I think that was the issue. I went back and realized I was moving the array then deleting the account, when I should've been removing the account then moving the array.
Last edited on
Topic archived. No new replies allowed.