102

If I have:

unsigned int x;
x -= x;

it's clear that x should be zero after this expression, but everywhere I look, they say the behavior of this code is undefined, not merely the value of x (until before the subtraction).

Two questions:

  • Is the behavior of this code indeed undefined?
    (E.g. Might the code crash [or worse] on a compliant system?)

  • If so, why does C say that the behavior is undefined, when it is perfectly clear that x should be zero here?

    i.e. What is the advantage given by not defining the behavior here?

Clearly, the compiler could simply use whatever garbage value it deemed "handy" inside the variable, and it would work as intended... what's wrong with that approach?

17
  • 3
    possible duplicate of Why does the C standard leave use of indeterminate variables undefined?
    – jscs
    Aug 14, 2012 at 23:51
  • 9
    @W'rkncacnter I disagree with that being a dupe. Regardless of whether what value it takes, the OP expects it to be zero after x -= x. The question is why accessing uninitialized values at all is UB.
    – Mysticial
    Aug 14, 2012 at 23:53
  • 6
    It's interesting that the statement x=0; is typically converted to xor x,x in assembly. It's almost the same as what you are trying to do here, but with xor instead of subtraction.
    – 0xFE
    Aug 14, 2012 at 23:57
  • 2
    'i.e. What is the advantage given by not defining the behavior here? ' -- I would have thought that the advantage of the standard not listing the infinity of expressions with values that don't depend on one or more variables to be obvious. At the same time, @Paul, such a change to the standard would not make programs and libraries any bigger.
    – Jim Balter
    Aug 15, 2012 at 0:12
  • 1
    @MaxBarraclough: I saw his comments; they don't contain any quotes from the standard to back them up, whereas people here have been quoting the standard. Note that another similar C expert there actually misremembered what the standard said about type-punning, and someone had to correct him. Did you see this comment below? It said this question was on the C committee's mailing list in 2015 and there was disagreement between the spec and their intentions. I think my summary captured it pretty darn accurately..
    – user541686
    Apr 18, 2020 at 22:38

7 Answers 7

104

Yes this behavior is undefined but for different reasons than most people are aware of.

First, using an unitialized value is by itself not undefined behavior, but the value is simply indeterminate. Accessing this then is UB if the value happens to be a trap representation for the type. Unsigned types rarely have trap representations, so you would be relatively safe on that side.

What makes the behavior undefined is an additional property of your variable, namely that it "could have been declared with register" that is its address is never taken. Such variables are treated specially because there are architectures that have real CPU registers that have a sort of extra state that is "uninitialized" and that doesn't correspond to a value in the type domain.

Edit: The relevant phrase of the standard is 6.3.2.1p2:

If the lvalue designates an object of automatic storage duration that could have been declared with the register storage class (never had its address taken), and that object is uninitialized (not declared with an initializer and no assignment to it has been performed prior to use), the behavior is undefined.

And to make it clearer, the following code is legal under all circumstances:

unsigned char a, b;
memcpy(&a, &b, 1);
a -= a;
  • Here the addresses of a and b are taken, so their value is just indeterminate.
  • Since unsigned char never has trap representations that indeterminate value is just unspecified, any value of unsigned char could happen.
  • At the end a must hold the value 0.

Edit2: a and b have unspecified values:

3.19.3 unspecified value
valid value of the relevant type where this International Standard imposes no requirements on which value is chosen in any instance

Edit3: Some of this will be clarified in C23, where the term "indeterminate value" is replaced by the term "indeterminate representation" and the term "trap representation" is replaced by "non-value representation". Note also that all of this is different between C and C++, which has a different object model.

48
  • 6
    Perhaps I'm missing something, but it seems to me that unsigneds can sure have trap representations. Can you point to the part of the standard that says so? I see in §6.2.6.2/1 the following: "For unsigned integer types other than unsigned char, the bits of the objectrepresentation shall be divided into two groups: value bits and padding bits (there need not be any of the latter). ... this shall beknown as the value representation. The values of any padding bits are unspecified. ⁴⁴⁾" with the comment saying: "⁴⁴⁾ Some combinations of padding bits might generate trap representations".
    – conio
    Dec 18, 2013 at 1:06
  • 6
    Continuing the comment: "Some combinations of padding bits might generate trap representations, for example, if one padding bit is a parity bit. Regardless, no arithmetic operation on valid values can generate a trap representation other than as part of an exceptional condition such as an overflow, and this cannot occur with unsigned types." - That's great once we have a valid value to work with, but the indeterminate value might be a trap representation before being initialized (e.g. parity bit set wrong).
    – conio
    Dec 18, 2013 at 1:09
  • 4
    @conio You're correct for all types other than unsigned char, but this answer is using unsigned char. Note though: a strictly conforming program can calculate sizeof(unsigned) * CHAR_BIT and determine, based on UINT_MAX, that particular implementations cannot possibly have trap representations for unsigned. After that program has made that determination, it can then proceed to do exactly what this answer does with unsigned char.
    – user743382
    Nov 27, 2014 at 11:38
  • 5
    @JensGustedt: Isn't the memcpy a distraction, i.e. wouldn't your example still apply if it were replaced by *&a = *&b;. Dec 21, 2015 at 21:28
  • 6
    @R.. I am not sure anymore. There is an ongoing discussion on the mailing list of the C committee, and it seems that all of this is a big mess, namely a large gap between what is (or has been) intended behavior and what is actually written up. What is clear though, is that accessing the memory as unsigned char and thus memcpy helps, the one for *& is less clear. I'll report once this settles down. Dec 22, 2015 at 15:27
26

The C standard gives compilers a lot of latitude to perform optimizations. The consequences of these optimizations can be surprising if you assume a naive model of programs where uninitialized memory is set to some random bit pattern and all operations are carried out in the order they are written.

Note: the following examples are only valid because x never has its address taken, so it is “register-like”. They would also be valid if the type of x had trap representations; this is rarely the case for unsigned types (it requires “wasting” at least one bit of storage, and must be documented), and impossible for unsigned char. If x had a signed type, then the implementation could define the bit pattern that is not a number between -(2n-1-1) and 2n-1-1 as a trap representation. See Jens Gustedt's answer.

Compilers try to assign registers to variables, because registers are faster than memory. Since the program may use more variables than the processor has registers, compilers perform register allocation, which leads to different variables using the same register at different times. Consider the program fragment

unsigned x, y, z;   /* 0 */
y = 0;              /* 1 */
z = 4;              /* 2 */
x = - x;            /* 3 */
y = y + z;          /* 4 */
x = y + 1;          /* 5 */

When line 3 is evaluated, x is not initialized yet, therefore (reasons the compiler) line 3 must be some kind of fluke that can't happen due to other conditions that the compiler wasn't smart enough to figure out. Since z is not used after line 4, and x is not used before line 5, the same register can be used for both variables. So this little program is compiled to the following operations on registers:

r1 = 0;
r0 = 4;
r0 = - r0;
r1 += r0;
r0 = r1;

The final value of x is the final value of r0, and the final value of y is the final value of r1. These values are x = -3 and y = -4, and not 5 and 4 as would happen if x had been properly initialized.

For a more elaborate example, consider the following code fragment:

unsigned i, x;
for (i = 0; i < 10; i++) {
    x = (condition() ? some_value() : -x);
}

Suppose that the compiler detects that condition has no side effect. Since condition does not modify x, the compiler knows that the first run through the loop cannot possibly be accessing x since it is not initialized yet. Therefore the first execution of the loop body is equivalent to x = some_value(), there's no need to test the condition. The compiler may compile this code as if you'd written

unsigned i, x;
i = 0; /* if some_value() uses i */
x = some_value();
for (i = 1; i < 10; i++) {
    x = (condition() ? some_value() : -x);
}

The way this may be modeled inside the compiler is to consider that any value depending on x has whatever value is convenient as long as x is uninitialized. Because the behavior when an uninitialized variable is undefined, rather than the variable merely having an unspecified value, the compiler does not need to keep track of any special mathematical relationship between whatever-is-convenient values. Thus the compiler may analyze the code above in this way:

  • during the first loop iteration, x is uninitialized by the time -x is evaluated.
  • -x has undefined behavior, so its value is whatever-is-convenient.
  • The optimization rule condition ? value : value applies, so this code can be simplified to condition; value.

When confronted with the code in your question, this same compiler analyzes that when x = - x is evaluated, the value of -x is whatever-is-convenient. So the assignment can be optimized away.

I haven't looked for an example of a compiler that behaves as described above, but it's the kind of optimizations good compilers try to do. I wouldn't be surprised to encounter one. Here's a less plausible example of a compiler with which your program crashes. (It may not be that implausible if you compile your program in some kind of advanced debugging mode.)

This hypothetical compiler maps every variable in a different memory page and sets up page attributes so that reading from an uninitialized variable causes a processor trap that invokes a debugger. Any assignment to a variable first makes sure that its memory page is mapped normally. This compiler doesn't try to perform any advanced optimization — it's in a debugging mode, intended to easily locate bugs such as uninitialized variables. When x = - x is evaluated, the right-hand side causes a trap and the debugger fires up.

5
  • +1 Nice explanation, the standard is taking special care of that situation. For a continuation of that story see my answer below. (too long to have as a comment). Aug 15, 2012 at 7:15
  • @JensGustedt Oh, your answer makes a very important point that I (and others) missed: unless the type has trap values, which for an unsigned type requires “wasting” at least one bit, x has an uninitialized value but the behavior on accessing would be defined if x didn't have register-like behavior. Aug 15, 2012 at 12:20
  • @Gilles: at least clang makes the kind of optimizations you mentioned: (1), (2), (3).
    – Vlad
    Aug 18, 2013 at 0:03
  • 1
    What practical advantage is there to having clang process things in that fashion? If downstream code never uses the value of x, then all operations on it could be omitted whether its value had been defined or not. If code following e.g. if (volatile1) x=volatile2; ... x = (x+volatile3) & 255; would be equally happy with any value 0-255 that x might contain in the case where volatile1 had yielded zero, I would think an implementation that would allow the programmer to omit an unnecessary write to x should be regarded as higher quality than one which would behave...
    – supercat
    May 29, 2018 at 20:06
  • ...in totally unpredictable fashion in that case. An implementation that would reliably raise an implementation-defined trap in that case might, for certain purposes, be regarded as being of higher quality yet, but behaving totally unpredictably seems to me like the lowest-quality form of behavior for pretty much any purpose.
    – supercat
    May 29, 2018 at 20:08
17

Yes, the program might crash. There might, for example, be trap representations (specific bit patterns which cannot be handled) which might cause a CPU interrupt, which unhandled could crash the program.

(6.2.6.1 on a late C11 draft says) Certain object representations need not represent a value of the object type. If the stored value of an object has such a representation and is read by an lvalue expression that does not have character type, the behavior is undefined. If such a representation is produced by a side effect that modifies all or any part of the object by an lvalue expression that does not have character type, the behavior is undefined.50) Such a representation is called a trap representation.

(This explanation only applies on platforms where unsigned int can have trap representations, which is rare on real world systems; see comments for details and referrals to alternate and perhaps more common causes which lead to the standard's current wording.)

16
  • 3
    @VladLazarenko: This is about C, not particular CPUs. Anyone can trivially design a CPU that has bit patterns for integers that drive it crazy. Consider a CPU that has a "crazy bit" in its registers. Aug 14, 2012 at 23:53
  • 2
    So can I say, then, that the behavior is well defined in case of integers and x86?
    – user405725
    Aug 14, 2012 at 23:55
  • 3
    Well, theoretically you could have a compiler which decided to only use 28-bits integers (on x86) and add specific code to handle each addition, multiplication (an so forth) and ensure that these 4 bits go unused (or emit a SIGSEGV otherwise). An uninitalized value could cause this.
    – eq-
    Aug 14, 2012 at 23:58
  • 4
    I hate when someone insults everyone else because that someone doesn't understand the issue. Whether the behavior is undefined is entirely a matter of what the standard says. Oh, and there is nothing at all practical about eq's scenario ... it's entirely contrived.
    – Jim Balter
    Aug 15, 2012 at 0:17
  • 8
    @Vlad Lazarenko: Itanium CPUs have a NaT (Not a Thing) flag for each integer register. The NaT Flag is used to control speculative execution and may linger in registers which aren't properly initialized before usage. Reading from such a register with a NaT bit set yields an exception. See blogs.msdn.com/b/oldnewthing/archive/2004/01/19/60162.aspx Aug 15, 2012 at 0:55
12

(This answer addresses C 1999. For C 2011, see Jens Gustedt’s answer.)

The C standard does not say that using the value of an object of automatic storage duration that is not initialized is undefined behavior. The C 1999 standard says, in 6.7.8 10, “If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate.” (This paragraph goes on to define how static objects are initialized, so the only uninitialized objects we are concerned about are automatic objects.)

3.17.2 defines “indeterminate value” as “either an unspecified value or a trap representation”. 3.17.3 defines “unspecified value” as “valid value of the relevant type where this International Standard imposes no requirements on which value is chosen in any instance”.

So, if the uninitialized unsigned int x has an unspecified value, then x -= x must produce zero. That leaves the question of whether it may be a trap representation. Accessing a trap value does cause undefined behavior, per 6.2.6.1 5.

Some types of objects may have trap representations, such as the signaling NaNs of floating-point numbers. But unsigned integers are special. Per 6.2.6.2, each of the N value bits of an unsigned int represents a power of 2, and each combination of the value bits represents one of the values from 0 to 2N-1. So unsigned integers can have trap representations only due to some values in their padding bits (such as a parity bit).

If, on your target platform, an unsigned int has no padding bits, then an uninitialized unsigned int cannot have a trap representation, and using its value cannot cause undefined behavior.

12
  • If x has a trap representation, then x -= x might trap, right? Still, +1 for pointing out unsigned integers with no extra bits must have defined behavior -- it's clearly the opposite of the other answers and (according to the quote) it seems to be what the standard implies.
    – user541686
    Aug 15, 2012 at 1:11
  • Yes, if the type of x has a trap representation, then x -= x might trap. Even simply x used as a value might trap. (It is safe to use x as an lvalue; writing into an object will not be affected by a trap representation that is in it.) Aug 15, 2012 at 1:33
  • unsigned types rarely have a trap representation Aug 15, 2012 at 7:08
  • Quoting Raymond Chen, "On the ia64, each 64-bit register is actually 65 bits. The extra bit is called “NaT” which stands for “not a thing”. The bit is set when the register does not contain a valid value. Think of it as the integer version of the floating point NaN. ... if you have a register whose value is NaT and you so much as breathe on it the wrong way (for example, try to save its value to memory), the processor will raise a STATUS_REG_NAT_CONSUMPTION exception". I.e., a trap bit can be completely outside the value. Apr 6, 2016 at 20:21
  • −1 The statement "If, on your target platform, an unsigned int has no padding bits, then an uninitialized unsigned int cannot have a trap representation, and using its value cannot cause undefined behavior." fails to consider schemes like the x64 NaT bits. Apr 6, 2016 at 20:26
12

For any variable of any type, which is not initialized or for other reasons holds an indeterminate value, the following applies for code reading that value:

  • In case the variable has automatic storage duration and does not have its address taken, the code always invokes undefined behavior [1].
  • Otherwise, in case the system supports trap representations for the given variable type, the code always invokes undefined behavior [2].
  • Otherwise if there are no trap representations, the variable takes an unspecified value. There is no guarantee that this unspecified value is consistent each time the variable is read. However, it is guaranteed not to be a trap representation and it is therefore guaranteed not to invoke undefined behavior [3].

    The value can then be safely used without causing a program crash, although such code is not portable to systems with trap representations.


[1]: C11 6.3.2.1:

If the lvalue designates an object of automatic storage duration that could have been declared with the register storage class (never had its address taken), and that object is uninitialized (not declared with an initializer and no assignment to it has been performed prior to use), the behavior is undefined.

[2]: C11 6.2.6.1:

Certain object representations need not represent a value of the object type. If the stored value of an object has such a representation and is read by an lvalue expression that does not have character type, the behavior is undefined. If such a representation is produced by a side effect that modifies all or any part of the object by an lvalue expression that does not have character type, the behavior is undefined.50) Such a representation is called a trap representation.

[3] C11:

3.19.2
indeterminate value
either an unspecified value or a trap representation

3.19.3
unspecified value
valid value of the relevant type where this International Standard imposes no requirements on which value is chosen in any instance
NOTE An unspecified value cannot be a trap representation.

3.19.4
trap representation
an object representation that need not represent a value of the object type

18
  • 3
    @Vality In the real world, 99.9999% of all computers are two's complement CPUs without trap representations. Therefore no trap representation is the norm and discussing the behavior on such real-world computers is highly relevant. To assume that wildly exotic computers is the norm isn't helpful. Trap representations in the real world are so rare that the presence of the term trap representation in the standard is mostly to be regarded as a standard defect inherited from the 1980s. As is support for one's complement and sign & magnitude computers.
    – Lundin
    Mar 9, 2017 at 7:37
  • 3
    By the way, this is an excellent reason why stdint.h should always be used instead of the native types of C. Because stdint.h enforces 2's complement and no padding bits. In other words, the stdint.h types aren't allowed to be full of crap.
    – Lundin
    Mar 9, 2017 at 7:40
  • 2
    Again the committee response to the defect report says that: "The answer to question 2 is that any operation performed on indeterminate values will have an indeterminate value as a result." and "The answer to question 3 is that library functions will exhibit undefined behavior when used on indeterminate values." Oct 2, 2017 at 11:35
  • 2
    DRs 451 and 260 Oct 2, 2017 at 11:37
  • 1
    @AnttiHaapala Yes I know of that DR. It doesn't contradict this answer. You may get an indeterminate value when reading an uninitialized memory location and it is not necessarily the same value every time. But that is unspecified behavior, not undefined behavior.
    – Lundin
    Oct 2, 2017 at 11:39
11

Yes, it's undefined. The code can crash. C says the behavior is undefined because there's no specific reason to make an exception to the general rule. The advantage is the same advantage as all other cases of undefined behavior -- the compiler doesn't have to output special code to make this work.

Clearly, the compiler could simply use whatever garbage value it deemed "handy" inside the variable, and it would work as intended... what's wrong with that approach?

Why do you think that doesn't happen? That's exactly the approach taken. The compiler isn't required to make it work, but it is not required to make it fail.

13
  • 1
    The compiler doesn't have to have special code for this either, though. Simply allocating the space (as always) and not intializing the variable gives it the correct behavior. I don't think that needs special logic.
    – user541686
    Aug 14, 2012 at 23:51
  • 7
    1) Sure, they could have. But I can't think of any argument that would make that any better. 2) The platform knows that the value of uninitialized memory cannot be relied on, so it's free to change it. For example, it can zero uninitialized memory in the background to have zeroed pages ready for use when needed. (Consider if this happens: 1) We read the value to subtract, say we get 3. 2) The page gets zeroed because it's uninitialized, changing the value to 0. 3) We do an atomic subtract, allocating the page and making the value -3. Oops.) Aug 14, 2012 at 23:59
  • 3
    -1 because you give no justification for your claim at all. There are situations where it would be valid to expect that the compiler just takes the value that is written in the memory location. Aug 15, 2012 at 7:18
  • 1
    @JensGustedt: I don't understand your comment. Can you please clarify? Aug 15, 2012 at 7:26
  • 3
    Because you just claim that there is a general rule, without refering to it. As such it is just an attempt of "proof by authority" which is not what I expect on SO. And for not effectively arguing why this couldn't be an unspecific value. The sole reason that this is UB in the general case is that x could be declared as register, that is that its address is never taken. I don't know if you were aware of that (if, you were hiding it effectively) but a correct answer must mention it. Aug 15, 2012 at 8:51
0

While many answers focus on processors that trap on uninitialized-register access, quirky behaviors can arise even on platforms which have no such traps, using compilers that make no particular effort to exploit UB. Consider the code:

volatile uint32_t a,b;
uin16_t moo(uint32_t x, uint16_t y, uint32_t z)
{
  uint16_t temp;
  if (a)
    temp = y;
  else if (b)
    temp = z;
  return temp;  
}

a compiler for a platform like the ARM where all instructions other than loads and stores operate on 32-bit registers might reasonably process the code in a fashion equivalent to:

volatile uint32_t a,b;
// Note: y is known to be 0..65535
// x, y, and z are received in 32-bit registers r0, r1, r2
uin32_t moo(uint32_t x, uint32_t y, uint32_t z)
{
  // Since x is never used past this point, and since the return value
  // will need to be in r0, a compiler could map temp to r0
  uint32_t temp;
  if (a)
    temp = y;
  else if (b)
    temp = z & 0xFFFF;
  return temp;  
}

If either volatile reads yield a non-zero value, r0 will get loaded with a value in the range 0...65535. Otherwise it will yield whatever it held when the function was called (i.e. the value passed into x), which might not be a value in the range 0..65535. The Standard lacks any terminology to describe the behavior of value whose type is uint16_t but whose value is outside the range of 0..65535, except to say that any action which could produce such behavior invokes UB.

14
  • Interesting. So are you saying the accepted answer is wrong? Or are you saying it's right in theory but in practice compilers may do weirder things?
    – user541686
    Aug 8, 2016 at 18:31
  • @Mehrdad: It is common for implementations to have behavior which goes beyond the bounds of what would be possible in the absence of UB. I think it would be helpful if the Standard recognized the concept of a partially-indeterminate value whose "allocated" bits will behave in a fashion that is, at worst, unspecified, but with additional upper bits that behave non-deterministically (e.g. if the result of the above function is stored to a variable of type uint16_t, that variable might sometimes read as 123 and sometimes 6553623). If the result ends up being ignored...
    – supercat
    Aug 8, 2016 at 18:42
  • ...or used in such a way that any possible ways it might be read would all yield final results meeting requirements, the existence of partially-indeterminate value shouldn't be a problem. On the other hand, there is nothing in the Standard which would allow for the existence of partially-indeterminate values in any circumstances where the Standard would impose any behavioral requirements whatsoever.
    – supercat
    Aug 8, 2016 at 18:44
  • It seems to me that what you are describing is exactly what is in the accepted answer -- that if a variable could have been declared with register, then it may have extra bits that make the behavior potentially undefined. That's exactly what you're saying, right?
    – user541686
    Aug 8, 2016 at 19:14
  • @Mehrdad: The accepted answer focuses on architectures whose registers have an extra "uninitialized" state, and trap if an uninitialized register is loaded. Such architectures exist, but are not commonplace. I describe a scenario where commonplace hardware may exhibit behavior which is outside the realm of anything contemplated by the C Standard, but would be usefully constrained if a compiler doesn't add its own additional wackiness to the mix. For example, if a function has a parameter that selects an operation to perform, and some operations return useful data but others don't,...
    – supercat
    Aug 8, 2016 at 19:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.