//---------------------------------------------------------------------------

#include <vcl.h>
#include <stdio.h>

#pragma hdrstop

#include "Unit1.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
	: TForm(Owner)
{
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
  char *myStoragePointers[4000];
  // allocation 1mb of characters
  try {
	try {
	  // null the pointers array
	  for (int i = 0; i < 4000; i++) {
		myStoragePointers[i] = NULL;
	  }
	  ProcessLabel->Caption = "Allocating Memory";
	  for (int i = 0; i < 4000; i++) {
		char *myStoragePointer = new char[1024*1024];
		myStoragePointers[i] = myStoragePointer; // save the pointer for later destruction
		sprintf(myStoragePointers[i], "%d", i);   // store something in the allocated memory
		MemBlockCountLabel->Caption = IntToStr(i); // keep track of memory allocated
		Application->ProcessMessages();
	  }
	}
	catch (const Exception& e) {
	  ProcessLabel->Caption = "Caught C++ Exception: " + e.Message;
	}
  }
  __finally {
	ProcessLabel->Caption = "Freeing Memory";
	for (int i = 0; i < 4000; i++) {
	  if (myStoragePointers[i] != NULL) {
		delete myStoragePointers[i];  // free the memory blocks
	  }
	}
  }
}
//---------------------------------------------------------------------------
