Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to explain undefined behavior to know-it-all newbies?

There'a a handful of situations that the C++ standard attributes as undefined behavior. For example if I allocate with new[], then try to free with delete (not delete[]) that's undefined behavior - anything can happen - it might work, it might crash nastily, it might corrupt something silently and plant a timed problem.

It's so problematic to explain this anything can happen part to newbies. They start "proving" that "this works" (because it really works on the C++ implementation they use) and ask "what could possibly be wrong with this"? What concise explanation could I give that would motivate them to just not write such code?

like image 443
sharptooth Avatar asked Feb 10 '10 08:02

sharptooth


People also ask

What happens undefined behavior?

In computer programming, undefined behavior (UB) is the result of executing a program whose behavior is prescribed to be unpredictable, in the language specification to which the computer code adheres.

What causes undefined Behaviour?

Undefined behavior is mostly based on the target it is intended to run on. The compiler is not responsible for the dynamic behavior of the program or the static behavior for that matter. The compiler checks are restricted to the rules of the language and some modern compilers do some level of static analysis too.

What does undefined behavior mean in C?

When we run a code, sometimes we see absurd results instead of expected output. So, in C/C++ programming, undefined behavior means when the program fails to compile, or it may execute incorrectly, either crashes or generates incorrect results, or when it may fortuitously do exactly what the programmer intended.

Does C# have undefined behavior?

The truly horrible kinds of Undefined Behavior which are encouraged in hypermodern C philosophy do not exist in C# or other .


1 Answers

Undefined means explicitly unreliable. Software should be reliable. You shouldn't have to say much else.

A frozen pond is a good example of an undefined walking surface. Just because you make it across once doesn't mean you should add the shortcut to your paper route, especially if you're planning for the four seasons.

like image 64
Alex Neth Avatar answered Sep 23 '22 11:09

Alex Neth