#include <iostream>

using namespace std;

// This example class is used for all examples in this section.

class BankAccount
{
public:
   BankAccount();
   void deposit(int amount);
   int get_balance() const;
private:
   int balance;
};

BankAccount::BankAccount()
   : balance(0)
{}

void BankAccount::deposit(int amount)
{
   balance = balance + amount;
}

int BankAccount::get_balance() const
{
   return balance;
}

// Here is an array of ten bank accounts, followed by an integer
// index. The variables are global to make the array corruption
// error happen reliably. You can make these into local variables
// and reproduce the error, but the details depend on the compiler.

BankAccount accounts[10];
int i;

int main()
{
   // in this loop, we "accidentally" run past the end of 
   // the array, by depositing money into the eleven accounts 
   // accounts[0] . . . accounts[10]

   for (i = 0; i <= 10; i++)
   {
      int amount = i * 1000;
      accounts[i].deposit(amount);

      cout << "Deposited " << amount << " into account " << i << endl;
   }

   return 0;
}

/*

Output:

Deposited 0 into account 0
Deposited 1000 into account 1
Deposited 2000 into account 2
Deposited 3000 into account 3
Deposited 4000 into account 4
Deposited 5000 into account 5
Deposited 6000 into account 6
Deposited 7000 into account 7
Deposited 8000 into account 8
Deposited 9000 into account 9
Deposited 10000 into account 10010


Explanation:

The memory layout looks like this:

accounts[0]
accounts[1]
. . .
accounts[9]
i               <---- this location is overwritten when 
                      accessing the invalid account[10]

*/
