Commit 332b61fe authored by Milo Yip's avatar Milo Yip

Handle malloc() fail in PoolAllocator

Fix #682
parent 2f751650
...@@ -179,7 +179,8 @@ public: ...@@ -179,7 +179,8 @@ public:
size = RAPIDJSON_ALIGN(size); size = RAPIDJSON_ALIGN(size);
if (chunkHead_ == 0 || chunkHead_->size + size > chunkHead_->capacity) if (chunkHead_ == 0 || chunkHead_->size + size > chunkHead_->capacity)
AddChunk(chunk_capacity_ > size ? chunk_capacity_ : size); if (!AddChunk(chunk_capacity_ > size ? chunk_capacity_ : size))
return NULL;
void *buffer = reinterpret_cast<char *>(chunkHead_) + RAPIDJSON_ALIGN(sizeof(ChunkHeader)) + chunkHead_->size; void *buffer = reinterpret_cast<char *>(chunkHead_) + RAPIDJSON_ALIGN(sizeof(ChunkHeader)) + chunkHead_->size;
chunkHead_->size += size; chunkHead_->size += size;
...@@ -211,11 +212,13 @@ public: ...@@ -211,11 +212,13 @@ public:
} }
// Realloc process: allocate and copy memory, do not free original buffer. // Realloc process: allocate and copy memory, do not free original buffer.
void* newBuffer = Malloc(newSize); if (void* newBuffer = Malloc(newSize)) {
RAPIDJSON_ASSERT(newBuffer != 0); // Do not handle out-of-memory explicitly. if (originalSize)
if (originalSize) std::memcpy(newBuffer, originalPtr, originalSize);
std::memcpy(newBuffer, originalPtr, originalSize); return newBuffer;
return newBuffer; }
else
return NULL;
} }
//! Frees a memory block (concept Allocator) //! Frees a memory block (concept Allocator)
...@@ -229,15 +232,20 @@ private: ...@@ -229,15 +232,20 @@ private:
//! Creates a new chunk. //! Creates a new chunk.
/*! \param capacity Capacity of the chunk in bytes. /*! \param capacity Capacity of the chunk in bytes.
\return true if success.
*/ */
void AddChunk(size_t capacity) { bool AddChunk(size_t capacity) {
if (!baseAllocator_) if (!baseAllocator_)
ownBaseAllocator_ = baseAllocator_ = RAPIDJSON_NEW(BaseAllocator()); ownBaseAllocator_ = baseAllocator_ = RAPIDJSON_NEW(BaseAllocator());
ChunkHeader* chunk = reinterpret_cast<ChunkHeader*>(baseAllocator_->Malloc(RAPIDJSON_ALIGN(sizeof(ChunkHeader)) + capacity)); if (ChunkHeader* chunk = reinterpret_cast<ChunkHeader*>(baseAllocator_->Malloc(RAPIDJSON_ALIGN(sizeof(ChunkHeader)) + capacity))) {
chunk->capacity = capacity; chunk->capacity = capacity;
chunk->size = 0; chunk->size = 0;
chunk->next = chunkHead_; chunk->next = chunkHead_;
chunkHead_ = chunk; chunkHead_ = chunk;
return true;
}
else
return false;
} }
static const int kDefaultChunkCapacity = 64 * 1024; //!< Default chunk capacity. static const int kDefaultChunkCapacity = 64 * 1024; //!< Default chunk capacity.
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment