Luigi Istratescu
Luigi Istratescu

Reputation: 97

Char variable goes Over the limit

I'm doing an intensive course in C++ and I am the kind of person that likes and wants to understand everything under the sun otherwise I can't continue with my homework.

char anything[5]{};
cin >> anything;
cout << anything << endl;

I can write 'Hello' in the console and it's all good. Writing 'H' is good too, and 'Hel' is good too. But what shouldn't be right is writing 'Helloo' or 'Hellooo', and it works! The moment I write 'Helloooooooooooooooooooooooooooooooo' program crashes, which is ok. This does the same when using numbers.

Why is this happening? I'm using CodeLite.

To my understanding, if I write over 5 characters the program shouldn't allow it, but it does.

What's the explanation behind this?

Upvotes: 0

Views: 84

Answers (1)

Asteroids With Wings
Asteroids With Wings

Reputation: 17454

[trigger warning: car crashes, amputations, cats]


if I write over 5 characters the program shouldn't allow it, but it does.

That's an overstatement.

The language doesn't allow it, but the compiler and runtime don't enforce that. That's because it would deduct from performance to perform bounds checking all the time just to look out for programmer errors, penalising those who didn't make any.

So, you broke a contract and what happens next is undefined. You could fall foul of some "optimisation" in the compiler that assumes you wrote a correct program; you could overwrite some memory at runtime, getting a crash; you could overwrite some memory at runtime, getting an apparently "valid" string up to the next NULL that happens to be there; or, you could open a wormhole to the local cattery. You just don't know.

This is called undefined behaviour.

An analogy would be driving over the speed limit. Your car won't stop you from speeding, but the law says not to, and if you do it anyway you may get arrested, or run someone over, or lose control then crash into a tree and lose all your limbs. Generally it's best not to take the chance.

Upvotes: 4

Related Questions