0

Below mention is my code. Please explain me why on negative index of array the IDE are printing either the garbage value or 0,instead of segmentation fault as we cannot access the negative indices in the array.

#include<iostream>
#include<vector>

using namespace std;

int main() {
   int n=10;
   int i=1;

   vector<int> arr(n,-1);
   // arr[i-2]=0;
   cout<<arr[i-2]<<endl;
   
   return 0;
}
paolo
  • 2,345
  • 1
  • 3
  • 17
  • 5
    It's undefined behavior. Anything can happen. And anything can be garbage values, 0, a segmentation fault or ordering pizza over the Internet. Unfortunately, by experiment I find that the latter is so unlikely that you shouldn't rely on it. – Thomas Weller Jul 08 '22 at 09:08
  • More precisely, accessing the negative indices in the array is an Undefined Behavior. –  Jul 08 '22 at 09:09
  • C++ says this is [undefined behaviour](https://en.cppreference.com/w/cpp/language/ub) not a segmentation fault. – john Jul 08 '22 at 09:11
  • There's no array in your code. You're calling `operator[]` of `std::vector`, which takes a `std::size_t` as parameter. So your `(int)-1` gets cast to `std::size_t` resulting in the maximum representable `std::size_t`, which is greater than `10`, hence out of bounds. – paolo Jul 08 '22 at 09:12
  • 2
    You have been misled if you think that C++ will behave predictably when you have bugs in your program. Most of the time when you break the C++ rules the behaviour of your entire program becomes undefined. – john Jul 08 '22 at 09:13
  • I spent 20 minutes of my life writing an in-depth answer to this question, just to realize it has been closed :) – thedemons Jul 08 '22 at 09:33

1 Answers1

1

A segmentation fault occurs in C++ when your program attempts to access memory not within the memory that the operating system allocated for your program. In other words, accessing memory that isn't yours.

According to the documentation for std::vector::operator[], under "Exception Safety", when accessing an index that is out of bounds, "the behavior is undefined". This means no checks are done.

Does this mean that a segmentation fault techically can occur? Yes. As the behaviour is undefined, it may just be that you are accessing memory that isn't yours, and a segmentation fault is signalled. As the behaviour is undefined, it might just be that the address you are trying to read is allocated to your program and can store 0, garbage, or any other value.

In practice, an error generally will not be thrown if you're trying to access the [-1] index of a vector or array, or if you go out of bounds. This is why a variety of undefined behaviour sanitizers, such as one made for Clang, are available to you. Upon undefined behaviour, these will raise an error and terminate your program.

Ryan Zhang
  • 1,856
  • 9
  • 19