Skip to main content

What happens when an array goes out of bounds?

Going out of an array's bounds means the program tries to access an element at an index that does not exist - for example, if the array has 5 elements, but the access is to A[5] or A[-2] (where only indices 0-4 are valid).


1. What this means technically

An array is stored in a contiguous memory area, and when it goes out of bounds the program starts accessing cells that do not belong to it. This means it reads or changes someone else's data in memory - memory allocated for other variables or system data.


2. What happens in different languages

LanguageReading arr[i] out of rangeWriting arr[i] = x out of rangeComment
JavaScript (Array)undefinedUsually extends the array (if i >= length), creates "holes"arr[-1] is not an index, but an object property (like arr["-1"])
TypeScriptSame as JS at runtimeSame as JS at runtimeTS can flag it with types, but doesn't change the behavior
Python (list)IndexErrorIndexErrorNegative indices are allowed: a[-1] is the last element
JavaArrayIndexOutOfBoundsExceptionArrayIndexOutOfBoundsExceptionBounds are always checked for arrays
C# (.NET)IndexOutOfRangeExceptionIndexOutOfRangeExceptionAlso checked for Span<T>/List<T>; can differ in unsafe
Go (slice/array)panic: runtime error: index out of rangepanicSlices are strictly checked
Rust (Vec/array)panic (with v[i]) / None (with v.get(i))panic (with v[i]=...)Idiomatic: use get() to avoid a panic
C (plain array)Undefined Behavior (may "work", may crash, may corrupt memory)Undefined BehaviorNo guarantees, possible vulnerabilities
C++ (operator[])Undefined BehaviorUndefined Behaviorstd::vector's at() throws std::out_of_range
Swift (Array)Runtime trap (crash)Runtime trap (crash)Safe wrappers/checks can be built
Kotlin (Array/List)IndexOutOfBoundsExceptionIndexOutOfBoundsExceptionOn the JVM, essentially the same as Java

3. Possible consequences

  • Program crash The system stops execution when it tries to access someone else's memory.
  • Data corruption The program can silently change variables in neighboring memory areas.
  • Vulnerabilities In low-level languages this can be exploited for hacking (buffer overflow).

4. Example

c
int a[3] = {10, 20, 30}; printf("%d", a[5]); // accessing a non-existent element

→ the program might print a random value, crash, or corrupt memory.


Summary:

When an array goes out of bounds, the program accesses memory it doesn't own. In "safe" languages this raises an error; in low-level languages it leads to unpredictable behavior or even a vulnerability.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.