Browse Source

[2088] Throw bad_alloc when MemorySegment cannot allocate the required space

Mukund Sivaraman 12 years ago
parent
commit
aa584b6a81

+ 3 - 0
src/lib/util/memory_segment.h

@@ -34,6 +34,9 @@ public:
     /// \brief Allocate/acquire a segment of memory. The source of the
     /// memory is dependent on the implementation used.
     ///
+    /// Throws <code>std::bad_alloc</code> if the implementation cannot
+    /// allocate the requested storage.
+    ///
     /// \param size The size of the memory requested in bytes.
     /// \return Returns pointer to the memory allocated.
     virtual void* allocate(size_t size) = 0;

+ 4 - 3
src/lib/util/memory_segment_local.cc

@@ -13,6 +13,7 @@
 // PERFORMANCE OF THIS SOFTWARE.
 
 #include "memory_segment_local.h"
+#include <new>
 
 namespace isc {
 namespace util {
@@ -20,11 +21,11 @@ namespace util {
 void*
 MemorySegmentLocal::allocate(size_t size) {
     void* ptr = malloc(size);
-
-    if (ptr != NULL) {
-        allocated_size_ += size;
+    if (ptr == NULL) {
+        throw std::bad_alloc();
     }
 
+    allocated_size_ += size;
     return (ptr);
 }
 

+ 3 - 0
src/lib/util/memory_segment_local.h

@@ -39,6 +39,9 @@ public:
     /// \brief Allocate/acquire a segment of memory. The source of the
     /// memory is libc's malloc().
     ///
+    /// Throws <code>std::bad_alloc</code> if the implementation cannot
+    /// allocate the requested storage.
+    ///
     /// \param size The size of the memory requested in bytes.
     /// \return Returns pointer to the memory allocated.
     virtual void* allocate(size_t size);

+ 6 - 0
src/lib/util/tests/memory_segment_local_unittest.cc

@@ -52,4 +52,10 @@ TEST(MemorySegmentLocal, TestLocal) {
     EXPECT_TRUE(segment->allMemoryDeallocated());
 }
 
+TEST(MemorySegmentLocal, TestTooMuchMemory) {
+    auto_ptr<MemorySegment> segment(new MemorySegmentLocal());
+
+    EXPECT_THROW(segment->allocate(0x7fffffffffffffff), bad_alloc);
+}
+
 } // anonymous namespace