Advertisement
mabrowning

Spot the bug(s)

Nov 20th, 2013
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.32 KB | None | 0 0
  1. #include <cstring>
  2. #include <iostream>
  3.  
  4. class Array
  5. {
  6. public:
  7.     Array()
  8.         : m_data (new int[10] )
  9.     {
  10.     }
  11.         ~Array()
  12.     {
  13.         delete[] m_data;
  14.     }
  15.    
  16.     Array & operator=( const Array & other)
  17.     {
  18.         memcpy( m_data, other.m_data, sizeof(4)*10 );
  19.         return *this;
  20.     }
  21.     int * m_data;
  22. };
  23.  
  24. class User
  25. {
  26. public:
  27.     User()
  28.     {
  29.     }
  30.    
  31.     ~User()
  32.     {
  33.     }
  34.    
  35.     User operator=( const User& other )
  36.     {
  37.         if(this == &other)return *this;
  38.         m_f1 = other.m_f1;
  39.         m_f2 = other.m_f2;
  40.         m_array = other.m_array;
  41.         return *this;
  42.     }
  43.    
  44.     int & getFirstOfArray()
  45.     {
  46.         return m_array.m_data[0];
  47.     }
  48.    
  49. private:
  50.     int m_f1;
  51.     double m_f2;
  52.     Array m_array;
  53. };
  54.  
  55. class Test
  56. {
  57. public:
  58.     void SetUser( const User & user )
  59.     {
  60.         m_user = user;
  61.     }
  62.     int & getFirstOfArray()
  63.     {
  64.         return m_user.getFirstOfArray();
  65.     }
  66. private:
  67.     User m_user;
  68.  
  69. };
  70.  
  71. int main(int argc, char** argv )
  72. {
  73.     Test test;
  74.     User newUser;
  75.     newUser.getFirstOfArray() = 255;
  76.     std::cout << newUser.getFirstOfArray() << std::endl;
  77.    
  78.     test.SetUser( newUser );
  79.     std::cout << test.getFirstOfArray() << std::endl; //invalid memory usage, potentially crash!
  80.  
  81.     return 0;
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement