HwTrap
HwTrap

Reputation: 303

Why Access Violation here?

I'm trying to construct my own class in some Delphi Project. The code is like this:

type
 TMyClass = class(TObject)
private
 hwnMain, hwnChild: HWND;
 Buffer, URL: string;
 Timer: TTimer;
public
 procedure ScanForClass;
end;

var
Form1: TForm1;
TimerAccess: TMyClass;

implementation

procedure TForm1.FormCreate(Sender: TObject);
begin
 TimerAccess.ScanForClass;
end;

procedure TMyClass.ScanForClass;
begin
 Timer:= TTimer.Create(Application); **here I get Access Violation!!**
 Timer.Interval:= 5000;
 Timer.Enabled:= true;

why getting that access violation?

Upvotes: 1

Views: 2357

Answers (1)

mjn
mjn

Reputation: 36634

Your code does not create an instance of the class before using it.

So it will raise a access violation Exception in this code:

procedure TForm1.FormCreate(Sender: TObject);
begin
  TimerAccess.ScanForClass;
end;

because TimerAccess is still uninitialized (undefined).

in FormCreate, call the constructor and assign the instance to the variable

procedure TForm1.FormCreate(Sender: TObject);
begin
  TimerAccess := TMyClass.Create; 
  TimerAccess.ScanForClass;
end;

in FormDestroy, call the destructor to cleanup:

procedure TForm1.FormDestroy(Sender: TObject);
begin
  TimerAccess.Free;
end;

Note: the code will not work if there are many instances of TForm1, because the variable TimerAccess is global, and every Form instance will assign a new instance of TMyClass in FormCreate, thus causing memory leaks. One solution would be to make TimerAccess a property (or field) of the Form class.

Upvotes: 14

Related Questions