Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Accessing Array Out of Bounds in C/C++



In a language such as Java, an exception such as java.lang.ArrayIndexOutOfBoundsException may occur if an array is accessed out of bounds. But there is no such functionality in C or C++, and undefined behavior may occur if an array is accessed out of bounds.

Accessing Out of Bound Memory

Accessing out of bounds means trying to access the array index that is greater than the array size and it will return any garbage value.

Example

In this example, an array 5 elements is initialized and we are trying to access 7 elements. In this case, it will print the first 5 array elements, and after that it will print garbage values.

C C++
#include<stdio.h>
int main()
{
    int arr[] = {1, 2, 3, 4, 5};
    printf("The elements of array : ");
    for (int i = 0; i < 7; i++)
        printf(" %d", arr[i]);
    return 0;
}

The output of the above code is as follows:

The elements of array :  1 2 3 4 5 32765
#include <iostream>
using namespace std;

int main()
{
   int arr[] = {1, 2, 3, 4, 5};
   cout << "The elements of array : ";
   for (int i = 0; i < 7; i++)
      cout << arr[i] << " ";
   return 0;
}

The output of the above code is as follows:

The elements of array : 1 2 3 4 5 0 -724676608

Out of Bound Memory Allocation

When we try to assign and access an array element at an index whose index is greater than the size of the element. It returns a segmentation fault.

Example

Here is an example of allocating out-of-bounds memory to an array in C and C++ that returns a segmentation fault in both cases:

C C++
#include<stdio.h>
int main()
{
    int arr[] = {1, 2, 3, 4, 5};
    arr[10] = 57;
    printf(" %d", arr[10]);
    return 0;
}

The output of the above code is as follows:

Segmentation fault (core dumped)
#include <iostream>
using namespace std;

int main()
{
   int arr[] = {1, 2, 3, 4, 5};
   arr[10] = 57;
   cout << arr[10];
   return 0;
}

The output of the above code is as follows:

Segmentation fault (core dumped)

Accessing Out of Bound Memory Using vector

The vector throws an error 'out_of_range' instead of giving any garbage value like arrays while accessing out of bound memory.

Example

In this example, we have a vector having five elements, and we are printing seven elements. This will throw an error as we are trying to access element greater than vector size.

#include <vector>
#include <iostream>
using namespace std;

int main()
{
   vector<int> v = {1, 2, 3, 4, 5};
   for (size_t i = 0; i < 7; ++i)
   {
      cout << v.at(i) << " ";
   }
   cout << endl;
   return 0;
}

The output of the above code will be an error that is displayed in the snippet below:

Output

Updated on: 2025-05-26T11:35:35+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements