Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Undefined behavior isn't necessarily leaving the compiler with multiple alternatives. Most commonly it is simply doing something that doesn't make sense.</p> <p>For example, take this code:</p> <pre><code>int arr[2]; arr[200] = 42; </code></pre> <p>this is undefined behavior. It's not that the compiler was given multiple alternatives to choose from. it's just that what I'm doing does not make sense. Ideally, it should not be allowed in the first place, but without potentially expensive runtime checking, we can't guarantee that something like this won't occur in our code. So in C++, the rule is simply that the language specifies only the behavior of a program that sticks to the rules. If it does something erroneous like in the above example, it is simply <em>undefined</em> what should happen.</p> <p>Now, imagine how you're going to detect this error. How is it going to surface? It might <em>never</em> seem to cause any problems. Perhaps we just so happen to write into memory that's mapped to the process (so we don't get an access violation), but is never otherwise used (so no other part of the program will read our garbage value, or overwrite what we wrote). Then it'll seem like the program is bug-free and works just fine.</p> <p>Or it might hit an address that's not even mapped to our process. Then the program will crash immediately. </p> <p>Or it might hit an address that's mapped to our process, but <em>at some point later</em> will be used for something. Then all we know is that sooner or later, the function reading from that address will get an unexpected value, and it'll behave weird. That part is easy to spot in the debugger, but it doesn't tell us anything about <em>when</em> or from <em>where</em> that garbage value was written. So there's no simple way to trace the error back to its source.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload