ArticleslgStudy

computer science

Bounds checking

Bounds checking is a computer science topic covered in the lgStudy science library. This page brings together a partial reference excerpt, illustrations, worked examples, real-world applications and a short study plan, so you can understand Bounds checking rather than just read about it. In short: In computer programming, bounds checking is any method of detecting whether a variable is within some bounds before it is used. It is usually used to ensure that a number fits into a given type (range checking), or that a variable being used as an array index is within the bounds of the array (index checking).

Key takeaways

  • Bounds checking belongs to computer science; place it in that map before memorising details.
  • Learn the definition first, then one example that makes the definition concrete.
  • Connect Bounds checking to a quantity you can measure, compute or draw — that is where exam questions come from.
  • Reproduce the core statement of Bounds checking from memory before moving on to harder problems.

Reference excerpt

In computer programming, bounds checking is any method of detecting whether a variable is within some bounds before it is used. It is usually used to ensure that a number fits into a given type (range checking), or that a variable being used as an array index is within the bounds of the array (index checking). A failed bounds check usually results in the generation of some sort of exception signal. As performing bounds checking during each use can be time-consuming, it is not always done. Bounds-checking elimination is a compiler optimization technique that eliminates unneeded bounds checking.

Range checking A range check confirms that a number is within a viable range for the program's functioning, such as ensuring that a value about to be assigned to a 16-bit integer is within the capacity of a 16-bit integer (i.e. checking against wrap-around). This is slightly different from type checking, which confirms that the data type is appropriate for the program's type system. Other range checks may be more restrictive; for example, a variable to hold the number of a calendar month may be declared to accept only the range 1 to 12. Example in Python:

Index checking Index checking means that, in all expressions indexing an array, the index value is checked against the bounds of the array (which were established when the array was defined), and if the index is out-of-bounds, further execution is suspended via some sort of error. Because reading or especially writing a value outside the bounds of an array may cause the program to malfunction or crash or enable security vulnerabilities (see buffer overflow), index checking is a part of many high-level languages. Early compiled programming languages with index checking ability included ALGOL 60, ALGOL 68 and Pascal, as well as interpreted programming languages such as BASIC. Many programming languages, such as C, never perform automatic bounds checking to raise speed. However, this leaves many off-by-one errors and buffer overflows uncaught. Many programmers believe these languages sacrifice too much for rapid execution. In his 1980 Turing Award lecture, C. A. R. Hoare described his experience in the design of ALGOL 60, a language that included bounds checking, saying:

A consequence of this principle is that every occurrence of every subscript of every subscripted variable was on every occasion checked at run time against both the upper and the lower declared bounds of the array. Many years later we asked our customers whether they wished us to provide an option to switch off these checks in the interest of efficiency on production runs. Unanimously, they urged us not to—they already knew how frequently subscript errors occur on production runs where failure to detect them could be disastrous. I note with fear and horror that even in 1980, language designers and users have not learned this lesson. In any respectable branch of engineering, failure to observe such elementary precautions would have long been against the law. Mainstream languages that enforce run time checking include Ada, Haskell, JavaScript, Lisp, PHP, Python, Ruby, and Visual Basic. The D and OCaml languages have run time bounds checking that is enabled or disabled with a compiler switch. In Java, exceptions are thrown on bounds checks: java.lang.IndexOutOfBoundsException is thrown on any collection bounds check, while its subclass java.lang.ArrayIndexOutOfBoundsException is thrown specifically for array bounds checks. C# similarly has System.IndexOutOfRangeException for arrays and System.ArgumentOutOfRangeException for collections, which are distinct exceptions. C# also supports unsafe blocks, which can temporarily suspend bounds checking to raise efficiency. These are useful for speeding up small time-critical bottlenecks without sacrificing the safety of a whole program. In Rust, raw indexing (i.e. v[i]) always performs a bounds check and thus incurs runtime cost, but can also be avoided entirely through iterators, which always stop at the end pointer. In C++, sequence collection types (such as std::vector, std::array, etc.) and string types (such as std::string) offer both operator[] and a at() method: the latter of which is always bounds-checked, and throws a std::out_of_range exception (while incurring a slight performance overhead). Since C++26, if a "hardened" standard library implementation is enabled, out-of-bounds access becomes a contract violation rather than just undefined behavior. The JS++ programming language is able to analyze if an array index or map key is out-of-bounds at compile time using existent types, which is a nominal type describing whether the index or key is within-bounds or out-of-bounds and guides code generation. Existent types have been shown to add only 1ms overhead to compile times.

Hardware bounds checking The safety added by bounds checking necessarily costs CPU time if the checking is performed in software; however, if the checks could be performed by hardware, then the safety can be provided "for free" with no runtime cost. An early system with hardware bounds checking was the ICL 2900 Series mainframe announced in 1974. The VAX computer has an INDEX assembly instruction for array index checking which takes six operands, all of which can use any VAX addressing mode. The B6500 and similar Burroughs computers performed bound checking via hardware, irrespective of which computer language had been compiled to produce the machine code. A limited number of later CPUs have specialised instructions for checking bounds, e.g., the CHK2 instruction on the Motorola 68000 series. Research has been underway since at least 2005 regarding methods to use x86's built-in virtual memory management unit to ensure safety of array and buffer accesses. In 2015 Intel provided their Intel MPX extensions in their Skylake processor architecture which stores bounds in a CPU register and table in memory. As of early 2017 at least GCC supports MPX extensions.

See also Dynamic code analysis Runtime error detection Static code analysis

References

… excerpt ends here. Continue reading the full article.

Worked examples

Example 1 — a first encounter with Bounds checking

Start with the simplest possible case. Write down what Bounds checking claims or describes in one sentence, then invent the smallest concrete situation in which that sentence is true. In computer science, the smallest case is usually a single object, a single equation or a single measurement. Check that every symbol or term in your sentence has a meaning in that case.

Example 2 — changing one variable

Take the situation from Example 1 and change exactly one quantity: double it, halve it, or set it to zero. Predict what should happen to Bounds checking before you calculate. Comparing your prediction with the result is the fastest way to find out whether you understand the idea or only the words.

Example 3 — an exam-style question

Typical questions about Bounds checking ask you to (a) state it precisely, (b) apply it to given data, and (c) explain a limitation. Practise writing all three answers in under five minutes; the third part is what separates a full-mark answer from an average one.

Applications of Bounds checking

In research
Bounds checking appears in computer science research whenever the underlying quantities have to be modelled precisely. Papers usually cite it as a starting assumption and then explore where it breaks down.
In technology and industry
Engineering practice reuses Bounds checking in design rules, simulations and safety margins. Knowing the idea lets you read a specification sheet and understand why the numbers look the way they do.
In the classroom
Bounds checking is common in secondary-school and first-year university syllabi. It links to neighbouring topics Arrays, Computer errors, so understanding it makes those chapters shorter.
In everyday life
Look for Bounds checking outside the textbook — in sport, cooking, traffic, electronics or the sky above you. An example you found yourself is remembered far longer than one you were given.
Ask Teacher Smith questions about this articleOpens your AI tutor with a question about “Bounds checking” →

How to study Bounds checking in 20 minutes

  1. Read the reference excerpt below once, without taking notes.
  2. Close the page and write down what Bounds checking means in your own words.
  3. Compare your version with the excerpt and mark what you missed.
  4. Work through the three examples above with pen and paper.
  5. Explain Bounds checking out loud to somebody else — or to Teacher Smith in the lgStudy chat.

Frequently asked questions

What is Bounds checking in simple terms?

In computer programming, bounds checking is any method of detecting whether a variable is within some bounds before it is used. It is usually used to ensure that a number fits into a given type (range checking), or that a variable being used as an array index is within the bounds of the array (inde…

Why does Bounds checking matter?

Because it connects several computer science ideas at once: it gives you a definition you can apply, a quantity you can calculate, and a way to check whether a result is plausible.

How should I study Bounds checking?

Read the excerpt, restate it from memory, then work through the examples and applications listed on this page. The five-step study plan above takes about twenty minutes.

What does this page cover?

It gives you a compact reference excerpt plus original lgStudy explanations, examples, applications and study material on Bounds checking.

Tags

  • Arrays
  • Computer errors

Keep exploring