Segmentation fault (core dumped)

#include <iostream>

void foo() {
    int* arr = new int[5];
    for (int i = 0; i <= 5; ++i) {
        arr[i] = i;
    }
    delete[] arr;
}

int main() {
    foo();
    return 0;
}
  1. A function foo is declared.
  2. Inside foo, a dynamic array arr of integers is created using new with a size of 5.
  3. A loop is used to fill the elements of arr with values from 0 to 5 (inclusive). The loop should run only for indices 0 to 4 to stay within the bounds of the array.
  4. The dynamic array is deleted using delete[] to free up the allocated memory.
  5. In the main function, foo is called.
  6. The program returns 0 to indicate successful execution.

The error in the code: - The loop in the foo function runs from 0 to 5 (inclusive), causing an out-of-bounds write when i is 5. This leads to undefined behavior and, in this case, results in a segmentation fault when the program tries to access memory beyond the allocated array.