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
What is out of bounds index in an array - C language?
In C programming, an out of bounds index occurs when you try to access an array element using an index that is beyond the valid range of the array. For an array of size n, valid indices range from 0 to n-1.
Syntax
datatype array[size]; // Valid indices: 0 to (size-1) // Out of bounds: any index < 0 or >= size
Understanding Array Bounds
If you declare an array with 4 elements, the valid indices are 0, 1, 2, and 3. Accessing index 4 or any higher value results in undefined behavior. The C compiler does not perform bounds checking, so out-of-bounds access compiles successfully but produces unpredictable results.
Example: Out of Bounds Access
The following program demonstrates what happens when we access an array beyond its bounds −
#include <stdio.h>
int main() {
int std[4];
int i;
// Valid assignments
std[0] = 100;
std[1] = 200;
std[2] = 300;
std[3] = 400;
// Invalid assignment (out of bounds)
std[4] = 500;
// Printing all elements including out-of-bounds
for(i = 0; i < 5; i++) {
printf("std[%d]: %d<br>", i, std[i]);
}
return 0;
}
std[0]: 100 std[1]: 200 std[2]: 300 std[3]: 400 std[4]: 500
Why This is Dangerous
While the above example might show the expected value 500, this behavior is undefined. The program might −
- Display garbage values
- Crash with a segmentation fault
- Overwrite other variables in memory
- Appear to work correctly but cause subtle bugs
Safe Array Access Example
Here's how to safely check array bounds before accessing elements −
#include <stdio.h>
#define ARRAY_SIZE 4
int main() {
int std[ARRAY_SIZE] = {100, 200, 300, 400};
int index;
// Safe access with bounds checking
for(index = 0; index < ARRAY_SIZE; index++) {
printf("std[%d]: %d<br>", index, std[index]);
}
// Example of checking before access
index = 5;
if(index < ARRAY_SIZE) {
printf("std[%d]: %d<br>", index, std[index]);
} else {
printf("Index %d is out of bounds!<br>", index);
}
return 0;
}
std[0]: 100 std[1]: 200 std[2]: 300 std[3]: 400 Index 5 is out of bounds!
Key Points
- C does not perform automatic bounds checking on arrays
- Out-of-bounds access leads to undefined behavior
- Always use loop conditions like
i < sizeinstead ofi <= size - Consider using static analysis tools or address sanitizers during development
Conclusion
Out of bounds array access is a common source of bugs and security vulnerabilities in C programs. Always ensure array indices stay within the valid range of 0 to size-1, and use proper bounds checking to prevent undefined behavior.
