From the course: Secure Coding in C

Unlock this course with a free trial

Join today to access over 25,600 courses taught by industry experts.

Accessing elements beyond the array size

Accessing elements beyond the array size - C Tutorial

From the course: Secure Coding in C

Accessing elements beyond the array size

- [Instructor] It's entirely possible in C to reference elements outside of an array's range, as demonstrated in this code. This array has three elements. They're numbered 0, 1, and 2. Here is a reference to element 3, the fourth element in the array, which doesn't exist. Build and run the code. Now, some compilers are smart enough to catch an array bounds problem, but not this one, and even so, it may just be a warning. This code builds and runs on this platform, outputting whatever garbage is in memory beyond the final array element. In this example, the array element is set by variable e. The element is still out of bounds, and in this case, it's way out of bounds. Build and run this one. Even on compilers that check for bounds, there will be no warning because a variable is used to set the value, and you see the output showing the garbage again, and the program didn't crash fortunately, but it could. One way to improve this code is to set a constant as the array's size, and remove…

Contents