28

In C or C++, it is very common to see questions like these asking about undefined behaviour. For those of you who don't usually use these languages: programming constructs that would usually produce errors in other languages (running off the end of an array, accessing deleted memory, and many many other programming errors) instead invoke "undefined behaviour" which means that anything effectively is permitted to happen (ranging from the program appearing to work, to outright crashes, to random jibberish on screen, etc.).

This is a really, really common topic for beginner programmers to get hung up on. They try a few permutations of their code (which is at this point exhibiting undefined behaviour), find out that some permutation accidentally causes their code to work, and post on SO hoping to understand why X works while Y doesn't.

They then get a nice answer saying that "well actually neither work, UB!". A lot of users seem deeply unsatisfied with this response. Lately I've been trying to explain in some way why these programs may behave in one way or another (e.g. explaining that it may be due to stack layout, or heap reuse, or some other factor), with the goal of trying to demystify this a bit.

I know the C/C++ specs don't say what happens, and in theory beginners should learn "pure" C/C++. But on the other hand, sometimes appreciating the underlying implementation details as I do may help to gain more insight into the code, and may help people avoid bad situations (since it is not always clear that something is UB).

Is this misguided? Should I just point them to "undefined behaviour" and leave it at that?

10
  • 2
    I've had success at explaining UB in HTML/CSS (yes, it exists) in terms of how a specific browser appears to be behaving compared to others - or better yet, how every browser seems to behave differently - but then again, not many of them were asked by beginners.
    – BoltClock Mod
    Commented Sep 15, 2014 at 3:24
  • 5
    Mention nasal demons at every opportunity. Commented Sep 15, 2014 at 18:32
  • 1
    @KevinPanko: I used to, but I'm fairly sure this was just bewildering to the newbies. I'm more inclined now to stick with "realistic" UB possibilities, which are still quite numerous (up to and including "someone pwns your computer").
    – nneonneo
    Commented Sep 15, 2014 at 18:33
  • @nneonneo I just like the mental image of a compiler causing unholy demons. Commented Sep 15, 2014 at 18:53
  • @BoltClock: I try to stretch the C++ UB concept to fit what you're describing there, but I can't. Wrong terminology? Looks Implementation-defined behaviour to me. Commented Sep 17, 2014 at 16:15
  • @Karoly Horvath: Yes, you could call it that.
    – BoltClock Mod
    Commented Sep 17, 2014 at 16:19
  • 1
    @BoltClock: should. Commented Sep 17, 2014 at 16:20
  • Talking about UB is strictly taboo in C++, has been for a long, long time. For a pretty good reason, it never produces anything constructive and most certainly doesn't ever make a C++ programmer any happier to be reminded about it. You can, at best, ask why it exists. Surely already answered btw. Commented Sep 17, 2014 at 17:03
  • @BoltClock, I thought the HTML parsing algorithm was well defined, and so there wouldn't be any undefined behaviour. Commented Feb 9, 2015 at 3:55
  • @Arturo Torres Sánchez: True, I was more referring to CSS rendering behavior, a lot of which is left undefined for various reasons.
    – BoltClock Mod
    Commented Feb 9, 2015 at 4:22

5 Answers 5

32

Perhaps clearly break your answer into two strictly separate parts? e.g.:

Your program accesses the value of buf before it's been initialized. The language doesn't specify what should happen in this case - you're invoking undefined behaviour. "Undefined" means the program is no longer guided by the language and could blah blah blah

You can't rely on this. You should treat it as an error.


In this case, it looks like the function works with the first set of input because the call to foo used that stack space for a different variable and set it to zero, which doesn't happen when blah blah blah

This is what's hiding the bug.

Nothing implementation-specific in the first part, just the theory-lecture. In the second part, what's actually going on. Keeping the two separate should give the lecture-part the opportunity to get the main point across, without distracting the asker with details of "actually here's how you can hack around it".

The other thing would be to make clear that UB isn't "sometimes valid", it's "sometimes seems valid because you tricked the compiler". In the above example, running foo hides a bug, but doesn't fix it; the bug is present but inert. Technically "undefined" is not "wrong", and that's the problem; but if the asker can't tell the difference, treating it as wrong will get the point across. They're not ready to take advantage of it if they need you to tell them when it's OK.

4
  • 1
    +1 For "This is what's hiding the bug." Still, I would conclude section 2 with: "This is what seems to be hiding the bug in this case." No need to go out on a limb at the end. Also, I really like to link my first mention of Undefined Behavior (UB) to Undefined, unspecified and implementation-defined behavior Commented Sep 15, 2014 at 12:49
  • 3
    This is basically the answer I was going to post. When I was learning C, explanations of "what actually happened with this CPU+OS+compiler" and "why it might be different on other implementations or with other environmental conditions" were really helpful in understanding why certain things are left undefined and why no particular behavior can be relied on. (I've always wanted to understand what's going on close to the metal, though. Everyone learns differently.)
    – zwol
    Commented Sep 15, 2014 at 17:44
  • This is basically what I already do, so of course I agree with the advice :)
    – nneonneo
    Commented Sep 15, 2014 at 18:32
  • Still, for most questions just saying it invokes UB and exactly why (that includes mentioning safe havens they just missed) and that all bets are off (best with a link to the UB-question) is a good answer. Also, the more the question goes into the details, the less an explanation of what UB means is worth, until it becomes essentially distracting fluff. Commented Sep 16, 2014 at 20:54
7

First, I agree with everything @Leushenko wrote. I wish however to add something to it.

I feel strongly that undefined behavior in C and C++ should be explained, not merely ruled out. There are at least three, distinct reasons:

  1. The very reason one uses C or C++ rather than, say, Java, is to program close to hardware. The algorithms may be similar in C/C++ and Java, but the mindset is very different. Programming Java, one might think of the physical machine as an incidental agent whose role it is to run the code. Programming C or C++ however, one might think of the compiler, and even the code it compiles, as incidental agents whose purpose it is to marshal and deploy machine instructions to the hardware. The one mindset is code- and algo-centric; the other is comparatively silicon-centric. (There are many non-silicon-centric C++ programmers, of course; but more than a few of these find C++ frustrating, and wish that they were programming in some other language. The silicon-centric programmer finds C++ liberating, which is my point.)

  2. C and C++ rule the important domain of embedded systems, in which the programming often really is about the hardware itself, about which the C and C++ standards speak in only a general way.

  3. Even if one would never ship code that purposely relied on undefined behavior, a deep understanding of undefined behavior is most useful during testing and debugging.

Undefined behavior is of course usually undesirable in C and C++ but, technically, it merely describes operations whose effects simply lie outside the compiler's purview. Consider: every kernel system call invokes undefined behavior!

Not all C/C++ programs call, or should call, the operating-system kernel; but more than a few do. Such programs have limited interest in portability, and are happy to be programmed in languages like C and C++.

Sometimes our answers on StackOverflow inadvertently leave the impression that undefined behavior were more or less arbitrary. Of course, it really isn't very arbitrary in most cases, but rather tends to be somewhat predictable if you understand stack pointers, memory managers, and the essential differences between machine architectures. Usually, a programmer does not want to worry about such things—except when he does. At any rate, the reasons underlying specific undefined behavior are often profitable for the C or C++ programmer to know, even if the programmer ought to avoid provoking undefined behavior in shipped code.

4
  • For what it's worth: I taught a one-semester C++-programming course to electrical-engineering undergraduates for four years. Naturally, my students were a specialized audience, but I had better success with my C++ students than I did with students in other courses I taught like electrical theory and electromagnetics. The reason for the success, I believe, is that we explained practically everything in the course using a stack or stack/heap diagram on the chalkboard. That's all about undefined behavior in a way, but you see, you can think about C++ that way. It works quite well.
    – thb
    Commented Sep 15, 2014 at 19:08
  • 2
    I'm inclined to think that it isn't sensible to try to explain the theory behind UB in each and every relevant question. Is there, or should there be, a canonical question we can link to? Commented Sep 16, 2014 at 3:57
  • @HarryJohnston: I already mentioned the question I often link to when I mention UB. The accepted answer has a good explanation for what UB might mean, for writing to constant literals, and why there are so completely disparate results. That might serve. Commented Sep 16, 2014 at 20:49
  • @HarryJohnston: You might be thinking from my answer that I disagreed, but I actually agree with you, completely for what it's worth.
    – thb
    Commented Sep 16, 2014 at 22:12
2

The root cause is that they don't understand the process of compiling a source program into object code, and they don't know how CPU instructions work or anything about computer architecture. I think people need to have at least a rudimentary understanding of these things in order to get UB.

0

One other thing to note about Undefined Behavior is that "It works on my compiler." is not justification for using it.

Since it is undefined, compiling your code with a different compiler may produce different results. Hence using U.B. means that when you port to a different environment, your program may start failing in mysterious ways.

Using a very simple and easy to understand example may help here:

int i = 3;
int a[5];
a[i] = i++;

is one such. The point being that you know that this will assign the value 3 somewhere, but depending on the order in which the compiler does things, that 3 could land in either a[3] or a[4] (or someplace else).

a[3] and a[4] are by far the most likely targets, but you really can't say which one. Hence the reason this is undefined, and therefore a bad idea.

-4

I think as it's such a common theme in C/C++, a short clear summary explanation (one/two sentence answer) will be fine with a link to a longer more thorough explanation if necessary. I think as long as new programmers understand the "why it's happening" they can apply it to their future learning to detect times in the future where UB strikes!

1
  • 2
    It would be better to find an existing question about the same misuse of the language, and close as a duplicate. Commented Sep 15, 2014 at 3:32

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .