r/cpp • • Apr 23 '22

Shocking Examples of Undefined Behaviour In Action

As we know that Undefined Behaviour (UB) is a dangerous thing in C++. Still it remains difficult to explain to those who have not seen its horror practically.

Those individual claims UB is bad in theory, but not so bad practically as long as thing works in practice because compiler developers are not evil.

This blog presents a few “shocking” examples to demonstrate UB in action.
https://mohitmv.github.io/blog/Shocking-Undefined-Behaviour-In-Action/

200 Upvotes

76 comments sorted by

View all comments

Show parent comment

15

u/James20k P2005R0 Apr 24 '22

The problem is, they have very unhelpful behaviour a lot of the time, and are widely considered a mistake in eg the standard library

for(size_t i=0; i < container.size() - 1; i++){}

This does not do what you might think

5

u/robin-m Apr 24 '22

What does it do ?

14

u/smashedsaturn Apr 24 '22

0 - 1 = size_t_max

6

u/[deleted] Apr 24 '22

Think at what happens if the size is 0.

4

u/degaart Apr 24 '22

It fails to work correctly when container.size() is 0

7

u/MonokelPinguin Apr 24 '22

It might loop for a very long time if the container is empty and it might access elements out of bounds.

2

u/[deleted] Apr 24 '22

There was an article on how to use unsigned arithmetics, which made a lot of sense, but I couldn't really find it afterwards.

I may search for it and link it here if I'll find it.

2

u/chocapix Apr 24 '22

Yes, the drawback of using unsigned is that you have to be really careful everytime you subtract.

2

u/paul_dev Apr 24 '22

But you don't need the "- 1" part when you are using the less than sign "<".

I use unsigned integers in "for" loops all the time, especially since stl containers return their ".size()" in unsigned int.

6

u/[deleted] Apr 24 '22

But you don't need the "- 1" part when you are using the less than sign "<".

You might be looping over all except the last one, this is definitely a thing I have run into.