I'm build an application that reducing the pixels width.
When I'm pressing the button of that application two or three times, Message will appear and say stack overflow.
Here's the Message :

Error Line on my application
Here's my code :
procedure TForm1.cariThin();
var
baris_gbr, kolom_gbr, x, y, a, b, i, j, p1, p2, n : integer;
imgval : array [0..500,0..500] of integer;
mark : array [0..500,0..500] of integer;
nb : array [1..9] of integer;
hasdelete: boolean;
R, G, BL, AB : integer;
begin
Image3.Width := Image1.Width;
Image3.Height := Image1.Height;
baris_gbr := Image1.Picture.Height;
kolom_gbr := Image1.Picture.Width;
For kolom_gbr:= 0 To image1.Width - 1 Do
Begin
For baris_gbr:= 0 To image1.Height - 1 Do
Begin
R:= GetRValue(image1.Canvas.Pixels[kolom_gbr, baris_gbr]);
G:= GetGValue(image1.Canvas.Pixels[kolom_gbr, baris_gbr]);
BL:= GetBValue(image1.Canvas.Pixels[kolom_gbr, baris_gbr]);
AB:= (R + G + BL) Div 3;
if (AB > 200) then
begin
Image1.Canvas.Pixels[kolom_gbr, baris_gbr] := rgb(255,255,255);
end
else
begin
Image1.Canvas.Pixels[kolom_gbr, baris_gbr] := rgb(0,0,0);
end;
End;
End;
for y := 0 to baris_gbr-1 do
begin
for x := 0 to kolom_gbr-1 do
begin
if (Image1.canvas.pixels[x,y] = clBlack) then
begin
imgval[x,y] := 1;
end
else
begin
imgval[x,y] := 0;
end;
end;
end;
hasdelete := True;
while (hasdelete) do
begin
hasdelete := False;
for y := 0 to baris_gbr-1 do
begin
for x := 0 to kolom_gbr-1 do
begin
if (imgval[x,y] = 1) then
begin
for n:=1 to 8 do
begin
nb[n] := 0;
nb[1] := imgval[x,y];
nb[2] := imgval[x,y-1];
nb[3] := imgval[x+1,y-1];
nb[4] := imgval[x+1,y];
nb[5] := imgval[x+1,y+1];
nb[6] := imgval[x,y+1];
nb[7] := imgval[x-1,y+1];
nb[8] := imgval[x-1,y];
nb[9] := imgval[x-1,y-1];
a := 0;
end;
for i:= 2 to 8 do
begin
if ((nb[i] = 0) AND (nb[i+1] = 1)) then
begin
inc(a);
end;
end;
if ((nb[9] = 0) AND (nb[2] = 1)) then
begin
inc(a);
end;
b := nb[2] + nb[3] + nb[4] + nb[5] + nb[6] + nb[7] + nb[8] + nb[9];
p1 := nb[2] * nb[4] * nb[6];
p2 := nb[4] * nb[6] * nb[8];
if ((a = 1) AND ((b>=2) AND (b <= 6)) AND (p1 = 0) AND (p2 = 0)) then
begin
mark[x,y] := 0;
hasdelete := true;
end
else
begin
mark[x,y] := 1;
end
end
else
begin
mark[x,y] := 0;
end;
end;
end;
for y:=0 to baris_gbr-1 do
begin
for x:=0 to kolom_gbr-1 do
begin
imgval[x,y] := mark[x,y];
end;
end;
end;
end;
Why my application keep says overflow? is there any solution to fix it? or can we can exception handler? thanks
EDIT
Now my pplication says access violation.

It raised error in this line : nb[7] := imgval[x-1,y+1];
why it exactly happened?
kolom_gbrandbaris_gbrvariables...forloop in your context. Once you use them in aforloop, they can get random values after. But e.g. instead offor kolom_gbr := 0 to image1.Width - 1 doyou could writefor x := 0 to kolom_gbr - 1 do.