0

I have code, in which I input each number on new line until I write 0. I am confused about size of array. In begining i declare that A is array with indices 1 to 5. But when I keep writing and put more than 5 numbers, it seems like it is still saved and then later used in second for cycle. How is that possible? I thought if i run out of indices I would get an error.

program testarray;
var hmez,                            
    i:integer;                           
    A:array [1..5] of integer;

begin
i:=0;
   repeat                                            
   inc(i);
   readln(A[i]); 
   if A[i]=0 then hmez:=i-1;
   until A[i]=0;
for i:=1 to hmez do
  writeln(A[i]);
end.

1 Answer 1

3

You are overwriting memory that doesn't belong to the A variable. This will sooner or later cause an unhandled exception (run-time error) or any other 'weird' behavior caused be the memory leak. Unlike from 'managed' languages such as C# or Java in Pascal run-time checking of array indices is an optional feature, not a mandatory, enforced, language feature.

Pascal compilers usually have an option to turn on or off array index checks which is called 'range checking'. The directive {$R+} turns on these range checks — see the documentation here.

In your case the code seems to 'work' only because, likely, there's no other useful variable placed in the memory after the space allocated for A. Please note this is just a conincidence and may not be that case in all runs of your program. So generally, your program as-is is incorrect.

Sign up to request clarification or add additional context in comments.

4 Comments

thank you, so you are suggesting to turn on range checks to make my program correct?
You should check if the index is valid in your code at the first place. Compiler-generated range checks are a safety net. However, yes, you should definitely have them turned on at all times.
Your program is incorrect in nature. Turning range checks on won't introduce correctness; it will let you know explicitly it's incorrect.
thank you once again, I actually increase the size via setlength function once the i>size of array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.