Adapted from: “Beej’s Guide to C Programming” by Brian (Beej Jorgensen) Hall: Beej’s Guide to C Programming: 6.4 Out of Bounds
Program for Demonstrating Out of Bounds Array Access¶
#include <stdio.h>
int main(void)
{
int i;
int a[5] = {22, 37, 3490, 18, 95};
for (i = 0; i < 10; i++) { // BAD NEWS: printing too many elements!
printf("%d\n", a[i]);
}
}Explanation of the Above Code¶
This C code demonstrates an example of accessing an array out of bounds, which is a common programming error. Here’s a breakdown:
Code Explanation:¶
#include <stdio.h>Includes the standard input/output library, which provides the
printffunction for printing to the console.
int main(void)The
mainfunction is the entry point of the program.
int i;
int a[5] = {22, 37, 3490, 18, 95};int i;: Declares a variableito be used as a loop counter.int a[5] = {22, 37, 3490, 18, 95};: Declares an integer arrayaof size 5 and initializes it with the values{22, 37, 3490, 18, 95}.
for (i = 0; i < 10; i++) { // BAD NEWS: printing too many elements!
printf("%d\n", a[i]);
}A
forloop is used to iterate through the arraya.i = 0: The loop starts withiset to 0.i < 10: The loop continues as long asiis less than 10.i++: Incrementsiby 1 after each iteration.
Inside the loop,
printf("%d\n", a[i]);prints the value of thei-th element of the arrayafollowed by a newline (\n).
Key Issue:¶
The array
ais declared with a size of 5, meaning it has valid indices from0to4.The loop iterates from
0to9, attempting to access elements beyond the bounds of the array (a[5]toa[9]).Accessing out-of-bounds elements results in undefined behavior in C. This could lead to:
Printing garbage values.
Crashing the program.
Overwriting memory, causing unpredictable behavior.
Output:¶
The first 5 iterations (
i = 0to4) will print the initialized values of the array:22 37 3490 18 95The remaining iterations (
i = 5to9) will likely print garbage values or cause a crash, depending on the memory layout.
Lesson:¶
Always ensure that array indices are within bounds to avoid undefined behavior.
Compile and Run Code¶
Use Python to Change to Working Directory¶
import os
root_dir = os.getcwd()code_dir = root_dir + "/" + "C_Code"os.chdir(code_dir)build_command = os.system("gcc -o section_6_4_out_of_bounds section_6_4_out_of_bounds.c")exec_status = os.system("./section_6_4_out_of_bounds")22
37
3490
18
95
0
0
7
1
0