Browse Source

[2726] Assign-to-self check

Michal 'vorner' Vaner 12 years ago
parent
commit
74625ee614
2 changed files with 15 additions and 8 deletions
  1. 10 8
      src/lib/util/buffer.h
  2. 5 0
      src/lib/util/tests/buffer_unittest.cc

+ 10 - 8
src/lib/util/buffer.h

@@ -342,15 +342,17 @@ public:
 
 
     /// \brief Assignment operator
     /// \brief Assignment operator
     OutputBuffer& operator =(const OutputBuffer& other) {
     OutputBuffer& operator =(const OutputBuffer& other) {
-        uint8_t* newbuff(static_cast<uint8_t*>(malloc(other.allocated_)));
-        if (newbuff == NULL && other.allocated_ != 0) {
-            throw std::bad_alloc();
+        if (this != &other) {
+            uint8_t* newbuff(static_cast<uint8_t*>(malloc(other.allocated_)));
+            if (newbuff == NULL && other.allocated_ != 0) {
+                throw std::bad_alloc();
+            }
+            free(buffer_);
+            buffer_ = newbuff;
+            size_ = other.size_;
+            allocated_ = other.allocated_;
+            std::memcpy(buffer_, other.buffer_, size_);
         }
         }
-        free(buffer_);
-        buffer_ = newbuff;
-        size_ = other.size_;
-        allocated_ = other.allocated_;
-        std::memcpy(buffer_, other.buffer_, size_);
         return (*this);
         return (*this);
     }
     }
 
 

+ 5 - 0
src/lib/util/tests/buffer_unittest.cc

@@ -248,6 +248,11 @@ TEST_F(BufferTest, outputBufferAssign) {
     });
     });
 }
 }
 
 
+// Check assign to self doesn't break stuff
+TEST_F(BufferTest, outputBufferAssignSelf) {
+    EXPECT_NO_THROW(obuffer = obuffer);
+}
+
 TEST_F(BufferTest, outputBufferZeroSize) {
 TEST_F(BufferTest, outputBufferZeroSize) {
     // Some OSes might return NULL on malloc for 0 size, so check it works
     // Some OSes might return NULL on malloc for 0 size, so check it works
     EXPECT_NO_THROW({
     EXPECT_NO_THROW({