Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Section 6.4 Arrays: Out of Bounds

Adapted from: “Beej’s Guide to C Programming” by Brian (Beej Jorgensen) Hall: Beej’s Guide to C Programming: 6.4 Out of Bounds

Brian (Beej Jorgensen) Hall Website

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 printf function for printing to the console.

int main(void)
  • The main function is the entry point of the program.

int i;
int a[5] = {22, 37, 3490, 18, 95};
  • int i;: Declares a variable i to be used as a loop counter.

  • int a[5] = {22, 37, 3490, 18, 95};: Declares an integer array a of 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 for loop is used to iterate through the array a.

    • i = 0: The loop starts with i set to 0.

    • i < 10: The loop continues as long as i is less than 10.

    • i++: Increments i by 1 after each iteration.

  • Inside the loop, printf("%d\n", a[i]); prints the value of the i-th element of the array a followed by a newline (\n).

Key Issue:

  • The array a is declared with a size of 5, meaning it has valid indices from 0 to 4.

  • The loop iterates from 0 to 9, attempting to access elements beyond the bounds of the array (a[5] to a[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 = 0 to 4) will print the initialized values of the array:

    22
    37
    3490
    18
    95
  • The remaining iterations (i = 5 to 9) 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