4

I was trying to produce an error for a try-catch testing with this code, where I expected to get an error when accessing a[3] (fourth) element. Even when not getting the error, the for loop must stop after five iterations, which never occurs.

int a[3] = {1, 2, 3};
for(int i = 0; i < 5; i++)
{
    std::cout << i << ": " << a[i] << std::endl;
}

output:

0: 1
1: 2
2: 3
3: 1970756548
4: 4201552
5: 2686800
6: 2130567168
7: 0
8: 0
9: 2686824
10: 4198992
.
.
.
4150: 0
4151: 0
4152: 0
4153: 0
4154: 0
LogicStuff
  • 19,397
  • 6
  • 54
  • 74
Adrian L
  • 41
  • 1
  • 6
    If this is gcc then see [C++ compilation bug?](http://stackoverflow.com/q/32506643/1708801) – Shafik Yaghmour Dec 10 '15 at 18:21
  • 3
    Nothing in your code has anything to do with "try-catch testing". The only ways to produce a catchable exceptions in C++ is: 1) use explicit `throw`, 2) use standard language features that are specified to throw a C++ exception. And out-of-bounds array access does not throw exceptions in C++. It produces undefiuned behavior. You can't use exception to catch undefined behavior. – AnT stands with Russia Dec 10 '15 at 18:25
  • take a look at the examples [here](http://en.cppreference.com/w/cpp/language/try_catch) to test out your try catch block – Noam Hacker Dec 10 '15 at 18:32

3 Answers3

8

It's undefined behavior(UB), you don't have (at least) five elements in your array. You cannot catch UB, exceptions is what we catch. Nothing more to debate here, but see the interesting link in the comments section.

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
LogicStuff
  • 19,397
  • 6
  • 54
  • 74
4

I was trying to produce an error for a try-catch testing with this code, where I expected to get an error when accessing a[3] (fourth) element. Even when not getting the error, the for loop must stop after five iterations, which never occurs.

You should not have expected an exception in such case. There is class of errors where exception doesn't occur (and even compiler is not required to tell you about this), but the program maybe still invalid. This is undefined behaviour.

Moreover you might not even notice the problem at the point where undefined behaviour happened, rather it may show itself later on.

Giorgi Moniava
  • 27,046
  • 9
  • 53
  • 90
0

A really simple answer is that you specified the start of an array (an address in memory), but continued traveling forwards from that address in memory - past your three array elements. C++ allows you to go out of bounds of an array and won't give you an exception. The problem is we don't know what will be in the memory after your three elements.

Here is a more detailed explanation of undefined behaviour - which other answers are referencing.

Community
  • 1
  • 1
Noam Hacker
  • 4,671
  • 7
  • 34
  • 55