C-Style Arrays

Out of Bounds Access in C-Style Arrays

What happens if I try to access an element outside the bounds of a C-style array?

Abstract art representing computer programming

When you attempt to access an element outside the bounds of a C-style array, you are invoking undefined behavior. This means that the language makes no guarantees about what will happen.

In practice, several things could occur:

  1. Your program might crash immediately with a segmentation fault.
  2. Your program might seem to work correctly, but you're actually accessing and modifying memory that doesn't belong to your array. This can lead to strange bugs that are hard to diagnose.
  3. Your program might behave differently every time you run it.

Here's an example:

int main() {
  int arr[3] = {1, 2, 3};
  
  //  Out of bounds access
  std::cout << arr[5];
}

In this case, arr[5] is accessing memory beyond the end of the array, which is undefined behavior.

To avoid this, always ensure your array accesses are within the valid bounds of the array. If you need runtime bounds checking, consider using std::vector or std::array instead, which offer .at() for bounds-checked access.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved