-3

I always thought if I accessed an array index greater than the array size that it would cause a runtime error? But it seems to be happy to run and output zero. Is this compiler specific or OS specific? Will some different environments cause a runtime error when you access an array index greater than the array size?

For eg;

int foo[5];
cout << foo[5] << endl;


vector<int> bar(5);
cout << bar[5] << endl;
sazr
  • 24,984
  • 66
  • 194
  • 362

3 Answers3

1

Accessing an array outside its bounds it's not a runtime error in C++: it's undefined behavior and it means that anything can happen, including nothing.

In C++ there are no "runtime error angels", only "undefined behavior daemons".

6502
  • 112,025
  • 15
  • 165
  • 265
1

Well, the code you provided is a classic example of undefined behaviour.

I always thought if I accessed an array index greater than the array size that it would cause a runtime error?

The vector class' .at(size_type pos) method performs a boundary check and throws std::out_of_range if pos is not within the range of the container.

vector#at documentation

Jonny Henly
  • 4,023
  • 4
  • 26
  • 43
paweldac
  • 1,144
  • 6
  • 11
0

it's undefined behavior trying to read or write beyond the bounds of the array , if it is a dynamic array the program may crash.

char c1[] = "123";
char c2[2] = "A"; // ok c2[0] = 'A', c2[1] = '\0';

cout << c1 << endl; // 123 ok
cout << c2 << endl; // A   ok

c2[5] = 'M'; // writing to the out bound of the array

cout << c1 << endl; // 1M3 ??!!
cout << c2 << endl; // A   ok

it causes memory dongling here.

Lee_Wong
  • 103
  • 1
  • 11