Jump to content
Registration disabled at the moment Read more... ×
John Kouraklis

Why does this code work when it shouldn't?

Recommended Posts

Check this code:

 

var
  forControl: Integer;
  forArrayDyn: array of Integer;

begin
  SetLength(forArrayDyn, 10);
  for forControl := 1 to 10 do
    forArrayDyn[forControl - 1]:=forControl;

  for forControl := 0 to Length(forArrayDyn)-1 do
  begin
    SetLength(forArrayDyn, 3);
    Writeln(forArrayDyn[forControl]);
  end;
end.

 

In the second for loop, the size of the forArrayDyn changes from 10 to 3 and yet the for loop is able to access the elements above index 2.

Given that for loops evaluate the initial and final values only once at the beginning of the loop, shouldn't this generate an AV?

I understand that in memory there are still elements in positions where index >=3 but shouldn't the code break?

The set length does affect the array because when I set a breakpoint I can see the change.

 

Thanks!

 

 

 

Share this post


Link to post

Resizing an array to a smaller length doesn't invalidate the other elements. You should have range checking on to catch this error.

  • Like 2

Share this post


Link to post

AV is when you access memory not belonging to your process. In this case you just access memory that is being freed but still belongs to the process. If you want array index control, enable range check

  • Like 1

Share this post


Link to post

Please sign in to comment

You will be able to leave a comment after signing in



Sign In Now

×