• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1Undefined Behavior
2------------------
3In the C language, some operations are undefined, like signed integer overflow,
4dereferencing freed pointers, accessing outside allocated space, ...
5
6Undefined Behavior must not occur in a C program, it is not safe even if the
7output of undefined operations is unused. The unsafety may seem nit picking
8but Optimizing compilers have in fact optimized code on the assumption that
9no undefined Behavior occurs.
10Optimizing code based on wrong assumptions can and has in some cases lead to
11effects beyond the output of computations.
12
13
14The signed integer overflow problem in speed critical code
15----------------------------------------------------------
16Code which is highly optimized and works with signed integers sometimes has the
17problem that some (invalid) inputs can trigger overflows (undefined behavior).
18In these cases, often the output of the computation does not matter (as it is
19from invalid input).
20In some cases the input can be checked easily in others checking the input is
21computationally too intensive.
22In these remaining cases a unsigned type can be used instead of a signed type.
23unsigned overflows are defined in C.
24
25SUINT
26-----
27As we have above established there is a need to use "unsigned" sometimes in
28computations which work with signed integers (which overflow).
29Using "unsigned" for signed integers has the very significant potential to
30cause confusion
31as in
32unsigned a,b,c;
33...
34a+b*c;
35The reader does not expect b to be semantically -5 here and if the code is
36changed by maybe adding a cast, a division or other the signedness will almost
37certainly be mistaken.
38To avoid this confusion a new type was introduced, "SUINT" is the C "unsigned"
39type but it holds a signed "int".
40to use the same example
41SUINT a,b,c;
42...
43a+b*c;
44here the reader knows that a,b,c are meant to be signed integers but for C
45standard compliance / to avoid undefined behavior they are stored in unsigned
46ints.
47
48