Advertisement
cwchen

[C++] lifetime error demo (undefined behavior)

Aug 27th, 2017
1,482
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.41 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using std::cout;
  4. using std::endl;
  5.  
  6. int main() {
  7.     int *x;
  8.  
  9.     {
  10.         // n become alive here
  11.         int n = 5;
  12.  
  13.         // Get the address of n
  14.         int* y = &n;
  15.  
  16.         // Share the address of n to x
  17.         x = y;
  18.     } // n lives until here
  19.  
  20.     // Now, assess n, which is no longer alive
  21.     // The behavior is undefined.
  22.     cout << *x << endl;
  23.  
  24.     return 0;
  25. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement