Questions tagged [undefined-behavior]

The unpredictable outcome of compiling or executing a program which breaks rules of the language neither compiler, interpreter nor runtime-system have to enforce. DO NOT USE this tag for questions regarding the data type or return value of "undefined". In those cases, the [undefined] tag should be used instead.

In computer programming, undefined behavior (informally "UB") refers to computer code whose behavior is not specified by the programming language standard under certain conditions.

The standards for some languages, most notably C and C++, leave certain aspects undefined, meaning the standard imposes no requirements whatsoever on the outcome. Implementations may regard such actions as erroneous, diagnosing them or not as they see fit, or may specify that they behave in some possibly-useful fashion without regard for whether the Standard requires them to do so.

For example, accessing beyond the last element of an array in C might be diagnosed by the compiler if the array index is known during compilation, or might return a garbage value from uninitialized memory, or return an apparently sensible value, or cause the program to crash by accessing memory outside the process' data address space.

Undefined Behavior most often causes confusion and controversy in situations where some parts of the Standard, an implementation's documentation, an earlier standard, or K&R's The C Programming Language describe the behavior of some action, but another part of the Standard characterizes the action as Undefined Behavior. In cases where the described behavior happens to be useful for the task at hand, the cost of behaving as described would often be less than the cost to the programmer of having to find some other way to accomplish the same task. In cases where it does not benefit the task at hand, however, upholding the behavior may add cost with no offsetting benefit. Because implementations are used for a variety of tasks with differing requirements, and because compiler writers should be better placed than the committee to know their various customers' needs, the authors of the Standard treat the question of whether to behave as described in such cases as a "quality of implementation" issue outside their jurisdiction.

Undefined behavior is commonly shortened to "UB". This informal abbreviation appears frequently in discussions regarding undefined behavior.

Formal definition of undefined behavior, as stated by the standards:

C11 3.4.3

undefined behavior
behavior, upon use of a nonportable or erroneous program construct or of erroneous data, for which this International Standard imposes no requirements

C++11 1.3.24

undefined behavior
behavior for which this International Standard imposes no requirements

[ Note: Undefined behavior may be expected when this International Standard omits any explicit definition of behavior or when a program uses an erroneous construct or erroneous data. Permissible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or without the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message). Many erroneous program constructs do not engender undefined behavior; they are required to be diagnosed. —end note ]

Tag usage

Use this tag for:

  • Questions asking if a certain code contains undefined behavior.
  • Questions regarding the various forms of documented undefined behavior in the given programming language.

Avoid using this tag for:

  • Questions asking why undefined behavior gave a certain result. It is often impossible to provide a meaningful answer to such questions.

Always use this tag together with the relevant programming language tag.

Useful C and C++ questions / canonical duplicates

How to explain undefined behavior to know-it-all newbies?
Undefined, unspecified and implementation-defined behavior.
Undefined behavior and sequence points.
Why are these constructs (using ++) undefined behavior?

External links

Wikipedia: Undefined behaviour
A Guide to Undefined Behavior in C and C++, Part 1
What Every C Programmer Should Know About Undefined Behavior, part 2, part 3
Isn't a Standard's whole job to standardize these things?
Implementation-defined, unspecified, and undefined behavior. What do these mean?
I just tried it on an ANSI-conforming compiler, and got the results I expected

2152 questions
132
votes
6 answers

Why does integer overflow on x86 with GCC cause an infinite loop?

The following code goes into an infinite loop on GCC: #include using namespace std; int main(){ int i = 0x10000000; int c = 0; do{ c++; i += i; cout << i << endl; }while (i > 0); cout << c <<…
Mysticial
  • 438,104
  • 44
  • 323
  • 322
126
votes
2 answers

When does invoking a member function on a null instance result in undefined behavior?

Consider the following code: #include struct foo { // (a): void bar() { std::cout << "gman was here" << std::endl; } // (b): void baz() { x = 5; } int x; }; int main() { foo* f = 0; f->bar(); // (a) …
119
votes
9 answers

How did I get a value larger than 8 bits in size from an 8-bit integer?

I tracked down an extremely nasty bug hiding behind this little gem. I am aware that per the C++ spec, signed overflows are undefined behavior, but only when the overflow occurs when the value is extended to bit-width sizeof(int). As I understand…
Unsigned
  • 8,731
  • 4
  • 40
  • 67
116
votes
8 answers

Is the "struct hack" technically undefined behavior?

What I am asking about is the well known "last member of a struct has variable length" trick. It goes something like this: struct T { int len; char s[1]; }; struct T *p = malloc(sizeof(struct T) + 100); p->len = 100; strcpy(p->s, "hello…
Evan Teran
  • 80,654
  • 26
  • 169
  • 231
113
votes
2 answers

Is passing a C++ object into its own constructor legal?

I am surprised to accidentally discover that the following works: #include int main(int argc, char** argv) { struct Foo { Foo(Foo& bar) { std::cout << &bar << std::endl; } }; Foo foo(foo); // I can't…
Andrew Wagner
  • 17,943
  • 18
  • 70
  • 92
99
votes
9 answers

Does "Undefined Behavior" really permit *anything* to happen?

The classic apocryphal example of "undefined behavior" is, of course, "nasal demons" — a physical impossibility, regardless of what the C and C++ standards permit. Because the C and C++ communities tend to put such an emphasis on the…
Kyle Strand
  • 14,120
  • 3
  • 59
  • 143
96
votes
2 answers

Is using malloc for int undefined behavior until C++20

I was told that the following code has undefined behavior until C++20: int *p = (int*)malloc(sizeof(int)); *p = 10; Is that true? The argument was that the lifetime of the int object is not started before assigning the value to it (P0593R6). To fix…
anton_rh
  • 5,990
  • 1
  • 31
  • 58
93
votes
3 answers

Printing null pointers with %p is undefined behavior?

Is it undefined behavior to print null pointers with the %p conversion specifier? #include int main(void) { void *p = NULL; printf("%p", p); return 0; } The question applies to the C standard, and not to C implementations.
Dror K.
  • 1,970
  • 14
  • 26
89
votes
8 answers

Can branches with undefined behavior be assumed unreachable and optimized as dead code?

Consider the following statement: *((char*)NULL) = 0; //undefined behavior It clearly invokes undefined behavior. Does the existence of such a statement in a given program mean that the whole program is undefined or that behavior only becomes…
usr
  • 162,013
  • 33
  • 219
  • 345
87
votes
12 answers

Detecting signed overflow in C/C++

At first glance, this question may seem like a duplicate of How to detect integer overflow?, however it is actually significantly different. I've found that while detecting an unsigned integer overflow is pretty trivial, detecting a signed overflow…
Channel72
  • 22,459
  • 30
  • 97
  • 168
87
votes
10 answers

Why does printf("%f",0); give undefined behavior?

The statement printf("%f\n",0.0f); prints 0. However, the statement printf("%f\n",0); prints random values. I realize I'm exhibiting some kind of undefined behaviour, but I can't figure out why specifically. A floating point value in which all…
Trevor Hickey
  • 31,728
  • 22
  • 131
  • 236
86
votes
12 answers

At what point in the loop does integer overflow become undefined behavior?

This is an example to illustrate my question which involves some much more complicated code that I can't post here. #include int main() { int a = 0; for (int i = 0; i < 3; i++) { printf("Hello\n"); a = a +…
jcoder
  • 28,098
  • 16
  • 76
  • 120
85
votes
4 answers

Is it legal for source code containing undefined behavior to crash the compiler?

Let's say I go to compile some poorly-written C++ source code that invokes undefined behavior, and therefore (as they say) "anything can happen". From the perspective of what the C++ language specification deems acceptable in a "conformant"…
Jeremy Friesner
  • 57,675
  • 12
  • 103
  • 196
85
votes
3 answers

Is signed integer overflow still undefined behavior in C++?

As we know, signed integer overflow is undefined behavior. But there is something interesting in C++11 cstdint documentation: signed integer type with width of exactly 8, 16, 32 and 64 bits respectively with no padding bits and using 2's complement…
Archie
  • 5,353
  • 2
  • 33
  • 42
84
votes
5 answers

Undefined behavior and sequence points reloaded

Consider this topic a sequel of the following topic: Previous installment Undefined behavior and sequence points Let's revisit this funny and convoluted expression (the italicized phrases are taken from the above topic *smile* ): i += ++i; We…
Nawaz
  • 327,095
  • 105
  • 629
  • 812