Danger of Array in C

This post is about the danger of uncareful usage of arrays in C.

October 12, 2024
Reading Time: 2 minutes

Introduction

Array or any form of it is a useful concept in C and any other languages. It helps us put a set of values in only one variable. It also demonstrates the power of the computer by allowing us to manipulate multiple values with loops and conditions. However, in C, there is a potential problem, that if the programmer missed, could potentially lead to unexpected behaviour of the computer.

Array out of bounds

This is the array out of bound usage. Placing values to each placeholder in an array is how we populate or update it. However, in C, we can put values to an array even if it already more than how many elements we declared it could contain.

If we declared an array that can contain 5 elements, for example as below:

#include <stdio.h>

int main() {
    static int arr[5];

    printf("%i", arr[10]);

    return 0;
}

And then if we accessed the element which has the index more than what we have, we will just get a warning.

This is the most that the compiler will give us. But when we try to put a value in an index of our array which is more than we have, we will not get an error.

Remember that in an array, we work with it through the addresses of each element that are next to each other. So if we, for example has an array with 5 elements and we accessed the 6th element, we will just have a warning but the program will give us a value. This value is the value next to the last element of our array.

What is the danger?

So what right? Well, if we are just reading the value of the out of bound element, we will just have that value whatever it is. The only problem for this is that our program will be wrong or will give us with unexpected result.

What if we are writing on it? This is the most where the problem will be. It is okay if the memory address that we are writing have no value in it. The problem will be what if there is! That part of the memory maybe being used by another software in the computer and we are trying to mess with it.

Conclusion

As we have seen the potential danger of this concept, programmers in C should be very careful in array manipulations if we want to program correctly and safely.