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;
}
- A function
foo
is declared. - Inside
foo
, a dynamic arrayarr
of integers is created usingnew
with a size of 5. - 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. - The dynamic array is deleted using
delete[]
to free up the allocated memory. - In the
main
function,foo
is called. - 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.