Skip to content

Commit

Permalink
Handle malloc() fail in PoolAllocator
Browse files Browse the repository at this point in the history
Fix #682
  • Loading branch information
miloyip committed Jul 21, 2016
1 parent 2f75165 commit 332b61f
Showing 1 changed file with 20 additions and 12 deletions.
32 changes: 20 additions & 12 deletions include/rapidjson/allocators.h
Original file line number Diff line number Diff line change
@@ -179,7 +179,8 @@ class MemoryPoolAllocator {

size = RAPIDJSON_ALIGN(size);
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;
chunkHead_->size += size;
@@ -211,11 +212,13 @@ class MemoryPoolAllocator {
}

// Realloc process: allocate and copy memory, do not free original buffer.
void* newBuffer = Malloc(newSize);
RAPIDJSON_ASSERT(newBuffer != 0); // Do not handle out-of-memory explicitly.
if (originalSize)
std::memcpy(newBuffer, originalPtr, originalSize);
return newBuffer;
if (void* newBuffer = Malloc(newSize)) {
if (originalSize)
std::memcpy(newBuffer, originalPtr, originalSize);
return newBuffer;
}
else
return NULL;
}

//! Frees a memory block (concept Allocator)
@@ -229,15 +232,20 @@ class MemoryPoolAllocator {

//! Creates a new chunk.
/*! \param capacity Capacity of the chunk in bytes.
\return true if success.
*/
void AddChunk(size_t capacity) {
bool AddChunk(size_t capacity) {
if (!baseAllocator_)
ownBaseAllocator_ = baseAllocator_ = RAPIDJSON_NEW(BaseAllocator());
ChunkHeader* chunk = reinterpret_cast<ChunkHeader*>(baseAllocator_->Malloc(RAPIDJSON_ALIGN(sizeof(ChunkHeader)) + capacity));
chunk->capacity = capacity;
chunk->size = 0;
chunk->next = chunkHead_;
chunkHead_ = chunk;
if (ChunkHeader* chunk = reinterpret_cast<ChunkHeader*>(baseAllocator_->Malloc(RAPIDJSON_ALIGN(sizeof(ChunkHeader)) + capacity))) {
chunk->capacity = capacity;
chunk->size = 0;
chunk->next = chunkHead_;
chunkHead_ = chunk;
return true;
}
else
return false;
}

static const int kDefaultChunkCapacity = 64 * 1024; //!< Default chunk capacity.

0 comments on commit 332b61f

Please sign in to comment.