undefined.txt 1.9 KB

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