SSJX.CO.UK
Browser Games | Cybiko | Amiga | Applications | Windows Games | Java Area | Test Area | Guides | Site Map

Out Of Bounds Testing

Introduction

This is part of a series testing each of the languages I use to see how good they are at catching simple array out of bounds errors.

Ideally most/all the errors should be picked up at compile time, if not the program should crash with an error. If the program keeps running, then it is trashing memory which can lead to security and stability problems.

The Tests

Currently I am testing for four potential errors. If we assume we have an array called 'myarray' that can hold 3 items:

  1. Typed out of bounds
    int myarray[3]	// Can hold 3 items 0,1,2
    myarray[3]=1
    

    This should be an easy catch as the index value is fixed and clearly outside the array.

  2. Constant index used to go out of bounds
    int myarray[3]	// Can hold 3 items 0,1,2
    const int idx=3
    myarray[idx]=1
    

    As the compiler will probably just replace the constant with the value, this should also be easy to catch. To the compiler, this error should be the same as error #1.

  3. Variable index that starts out of bounds
    int myarray[3]	// Can hold 3 items 0,1,2
    int idx=3
    myarray[idx]=1
    

    This one I do not really expect to be caught as the variable index could be changed elsewhere in the program.

  4. A loop that goes out of bounds
    int myarray[3]	// Can hold 3 items 0,1,2
    for idx=0 to 5
    {
       myarray[idx]=1
    }
    

    Not sure if this one would be caught, the problem is that some languages let you change the loop index mid loop. That said, the compiler could give a warning as the highest value would be outside the array. Note: In practice and where possible, a range based loop is generally safer for using with arrays.

Languages / Compilers Tested

Conclusion

Some languages have better defaults than others and changing the language you use may be beneficial. Whatever language you use though, make sure you turn on any checks that are available if they are not on by default.

11/01/20