Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Accessing array out of bounds in C/C++
An array in C is a fixed-size sequential collection of elements of the same data type where all elements are stored in contiguous memory. When an array is accessed out of bounds, undefined behavior occurs in C, unlike higher-level languages that throw exceptions.
Syntax
type arrayName[size]; // Valid indices: 0 to (size-1) // Out of bounds: index < 0 or index >= size
Accessing Out of Bounds Memory
Accessing out-of-bounds memory means trying to access an array index outside its valid range (index < 0 or index >= array size). This returns garbage values from adjacent memory locations.
Example: Reading Beyond Array Bounds
In this example, an array of 5 elements is initialized and we attempt to access 7 elements −
#include <stdio.h>
int main() {
int arr[] = {1, 2, 3, 4, 5};
printf("The elements of array: ");
for (int i = 0; i < 7; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
The elements of array: 1 2 3 4 5 32765 0
The first 5 elements are valid, while indices 5 and 6 contain garbage values from uninitialized memory.
Out of Bounds Array Assignment
Writing to memory outside an array's bounds can corrupt adjacent data structures or cause segmentation faults, depending on the memory location accessed.
Example: Writing Beyond Array Bounds
Here we attempt to assign a value at index 10 when the array size is only 5 −
#include <stdio.h>
int main() {
int arr[] = {1, 2, 3, 4, 5};
arr[10] = 57; // Writing beyond bounds
printf("Value at arr[10]: %d\n", arr[10]);
return 0;
}
Segmentation fault (core dumped)
Prevention Methods
Always validate array indices before access to prevent undefined behavior −
#include <stdio.h>
#define ARRAY_SIZE 5
int main() {
int arr[] = {1, 2, 3, 4, 5};
int index = 7;
if (index >= 0 && index < ARRAY_SIZE) {
printf("arr[%d] = %d\n", index, arr[index]);
} else {
printf("Error: Index %d is out of bounds (0-%d)\n", index, ARRAY_SIZE-1);
}
return 0;
}
Error: Index 7 is out of bounds (0-4)
Key Points
- C does not perform automatic bounds checking on arrays
- Reading out of bounds returns garbage values
- Writing out of bounds can cause segmentation faults or memory corruption
- Always validate array indices before access
Conclusion
Array bounds checking is the programmer's responsibility in C. Out-of-bounds access leads to undefined behavior, which can manifest as garbage values or program crashes. Always validate indices to ensure safe array access.
