code_junkie

What are all the common undefined behaviour that a C++ programmer should know about?

Nov 12th, 2011
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.10 KB | None | 0 0
  1. a[i] = i++;
  2.  
  3. // This expression has three parts:
  4. (a) a[i]
  5. (b) i++
  6. (c) Assign (b) to (a)
  7.  
  8. // (c) is guaranteed to happen after (a) and (b)
  9. // But (a) and (b) can be done in either order.
  10. // See n2521 Section 5.17
  11. // (b) increments i but returns the original value.
  12. // See n2521 Section 5.2.6
  13. // Thus this expression can be written as:
  14.  
  15. int rhs = i++;
  16. int lhs& = a[i];
  17. lhs = rhs;
  18.  
  19. // or
  20. int lhs& = a[i];
  21. int rhs = i++;
  22. lhs = rhs;
  23.  
  24. A* a = new A("plop");
  25.  
  26. // Looks simple enough.
  27. // But this can be split into three parts.
  28. (a) allocate Memory
  29. (b) Call constructor
  30. (c) Assign value to 'a'
  31.  
  32. // No problem here:
  33. // The compiler is allowed to do this:
  34. (a) allocate Memory
  35. (c) Assign value to 'a'
  36. (b) Call constructor.
  37. // This is because the whole thing is between two sequence points.
  38.  
  39. // So what is the big deal.
  40. // Simple Double checked lock. (I know there are many other problems with this).
  41. if (a == null) // (Point B)
  42. {
  43. Lock lock(mutex);
  44. if (a == null)
  45. {
  46. a = new A("Plop"); // (Point A).
  47. }
  48. }
  49. a->doStuff();
  50.  
  51. // Think of this situation.
  52. // Thread 1: Reaches point A. Executes (a)(c)
  53. // Thread 1: Is about to do (b) and gets unscheduled.
  54. // Thread 2: Reaches point B. It can now skip the if block
  55. // Remember (c) has been done thus 'a' is not NULL.
  56. // But the memory has not been initialized.
  57. // Thread 2 now executes doStuff() on an uninitialized variable.
  58.  
  59. // The solution to this problem is to move the assignment of 'a'
  60. // To the other side of the sequence point.
  61. if (a == null) // (Point B)
  62. {
  63. Lock lock(mutex);
  64. if (a == null)
  65. {
  66. A* tmp = new A("Plop"); // (Point A).
  67. a = tmp;
  68. }
  69. }
  70. a->doStuff();
  71.  
  72. // Of course there are still other problems because of C++ support for
  73. // threads. But hopefully these are addresses in the next standard.
  74.  
  75. // The simple obvious one.
  76. callFunc(getA(),getB());
  77.  
  78. int a = getA();
  79. int b = getB();
  80. callFunc(a,b);
  81.  
  82. int b = getB();
  83. int a = getA();
  84. callFunc(a,b);
  85.  
  86. const int i = 10;
  87. int *p = const_cast<int*>( &i );
  88. *p = 1234; //Undefined
  89.  
  90. int i =1;
  91. i = ++i;
  92.  
  93. // Undefined. Assignment to i twice in the same expression.
Add Comment
Please, Sign In to add comment