0

I have got a strange behaviour in my C++ code in VS19. I have the following code:

bool tru;
int ax[3] = { 1,2,3 };
int val = ax[5];
tru = (ax[5] == 1);

When I run this I get:

enter image description here

I would expect to get an error in line 3 but I get a[5] = 0xcccccccc. In this case tru = false would be correct. I have been using Qt Creator before which would crash in this case.

Can someone explain this behavior of Vs2019 to me?

GSerg
  • 76,472
  • 17
  • 159
  • 346
user3443063
  • 1,455
  • 4
  • 23
  • 37
  • 2
    Undefined behavior is undefined. It might crash, it might not, either way it is incorrect and the programmer is responsible to make sure that doesn't happen. 0xCC is one of the special values the debug heap will set memory to. https://stackoverflow.com/a/370362/920069 – Retired Ninja Nov 07 '21 at 07:43
  • 2
    This is one example of `C makes it easy to shoot yourself in the foot; C++ makes it harder, but when you do it blows your whole leg off"` . You have *undefined behavior* and anything can happen. – Jason Nov 07 '21 at 07:43
  • 2
    *I would expect to get an error* -- What kind of error were you expecting? A crash? A popup window saying you did something wrong? Regardless, all of that requires C++ to check array boundaries, and C++ does no checking of such. – PaulMcKenzie Nov 07 '21 at 07:57
  • 1
    *I have been using Qt Creator before which would crash in this case.* -- In C++, there is a concept called *undefined behavior*. There is nothing "strange" about what you are seeing -- when you write code that accesses an element outside the bounds of an array, access an uninitialized pointer, or do a whole host of other things that are too many to name, the behavior of the program becomes undefined. You were mistaken to think that C++ checks for things like this -- it doesn't. That's where you must be aware of this, and gain the experience of identifying these issues in your code. – PaulMcKenzie Nov 07 '21 at 08:05

0 Answers0