What Is Bounds Checking?
Boundary checking in program design refers to checking whether a variable is within a specific range before using it. The most common is subscript checking of arrays to prevent subscripts from exceeding the range of the array and overwriting other data. If the boundary check fails to find the error effectively, the most common result is that the program is abnormal and terminates, but other phenomena may also occur. Because boundary checking every time is very time consuming, and some code is sure that there will be no cross-boundary problems, this operation does not always need to be performed. Some modern compilers have a technique called selective boundary checking, which can omit some common unnecessary boundary checks, thereby improving the performance of the program.
- In common
- Range checking is often used to ensure that a number is within a specific range. This check is usually performed when accessing the array, because when the array subscript crosses the boundary, the data will be written into the space of other variables, and even overwrite the register value on the stack. As a result, the program may crash or cause some security holes. In Java, the Java virtual machine will automatically perform an array boundary check when attempting to access an element in an array, and raise an exception when the subscript crosses the boundary.
- Another common use of range checking is when two data types are converted to each other. In languages built on the .NET Framework, out-of-range coercion will throw an Invalid Cast Exception type exception.
- For example, before coercing a 32-bit signed integer variable to a 16-bit signed integer variable, it will check whether the value of this variable is between -32768 ~ + 32767 (16-bit signed integer can represent Range) instead of unrepresentable numbers such as 32768.