How to Fix Array Out of Bounds Access Errors
In this tutorial, you'll learn about How to Fix Array Out of Bounds Access Errors. We cover key concepts, practical examples, and best practices.
Array out of bounds errors occur when code accesses an index less than 0 or greater than or equal to the array length. In C and C++, this causes undefined behavior. In Java, Python, and Rust, it throws an exception or panics at runtime.
Quick Fix
Wrong
int arr[5] = {10, 20, 30, 40, 50};
for (int i = 0; i <= 5; ++i) {
std::cout << arr[i] << " ";
}
10 20 30 40 50 32767
The loop condition i <= 5 accesses index 5, which is past the end. Output may include garbage or crash.
Right
int arr[5] = {10, 20, 30, 40, 50};
for (int i = 0; i < 5; ++i) {
std::cout << arr[i] << " ";
}
10 20 30 40 50
Fix with bounds checking
#include <vector>
#include <stdexcept>
int safeAccess(const std::vector<int>& arr, size_t index) {
if (index >= arr.size()) {
throw std::out_of_range("Index " + std::to_string(index)
+ " out of range for array size " + std::to_string(arr.size()));
}
return arr[index];
}
Fix for off-by-one in C strings
char buf[10];
strcpy(buf, "hello"); // space for 10 is fine
// Wrong: no null terminator room
char buf2[5];
strcpy(buf2, "hello"); // overflow! needs 6 chars for null terminator
// Right:
char buf3[6] = "hello";
Prevention
- Use
std::vector::at()instead ofoperator[]for bounds-checked access. - Use range-based for loops where possible.
- Use
std::arraywithsize()method. - In C, use
snprintfinstead ofsprintf,strncpyinstead ofstrcpy. - Enable address sanitizer (
-fsanitize=address) during testing.
DodaTech Tools
Doda Browser's memory safety checker detects out-of-bounds access patterns in codebases. DodaZIP archives sanitizer reports for debugging. Durga Antivirus Pro detects buffer overflow exploits targeting array bounds.
Common Mistakes with array out of bounds
- Using
foldlinstead offoldl'causing stack overflow on large lists - Forgetting
deriving (Show, Eq)on custom data types needed for debugging - Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
These mistakes appear frequently in real-world DS code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro