AllocatorLog: support nulls in deallocate() and reallocate()

This commit is contained in:
Benoit Blanchon
2023-07-17 14:46:00 +02:00
parent c4e5051a7a
commit 65c67d317a
2 changed files with 8 additions and 5 deletions

View File

@ -109,18 +109,17 @@ class SpyingAllocator : public ArduinoJson::Allocator {
void deallocate(void* p) override { void deallocate(void* p) override {
auto block = AllocatedBlock::fromPayload(p); auto block = AllocatedBlock::fromPayload(p);
log_ << AllocatorLog::Deallocate(block->size); log_ << AllocatorLog::Deallocate(block ? block->size : 0);
upstream_->deallocate(block); upstream_->deallocate(block);
} }
void* reallocate(void* p, size_t n) override { void* reallocate(void* p, size_t n) override {
auto block = AllocatedBlock::fromPayload(p); auto block = AllocatedBlock::fromPayload(p);
auto oldSize = block->size; auto oldSize = block ? block->size : 0;
block = reinterpret_cast<AllocatedBlock*>( block = reinterpret_cast<AllocatedBlock*>(
upstream_->reallocate(block, sizeof(AllocatedBlock) + n - 1)); upstream_->reallocate(block, sizeof(AllocatedBlock) + n - 1));
if (block) { if (block) {
log_ << AllocatorLog::Reallocate(oldSize, n); log_ << AllocatorLog::Reallocate(oldSize, n);
ARDUINOJSON_ASSERT(block->size == oldSize);
block->size = n; block->size = n;
return block->payload; return block->payload;
} else { } else {
@ -143,6 +142,8 @@ class SpyingAllocator : public ArduinoJson::Allocator {
char payload[1]; char payload[1];
static AllocatedBlock* fromPayload(void* p) { static AllocatedBlock* fromPayload(void* p) {
if (!p)
return nullptr;
return reinterpret_cast<AllocatedBlock*>( return reinterpret_cast<AllocatedBlock*>(
// Cast to void* to silence "cast increases required alignment of // Cast to void* to silence "cast increases required alignment of
// target type [-Werror=cast-align]" // target type [-Werror=cast-align]"

View File

@ -31,8 +31,10 @@ class ArmoredAllocator : public Allocator {
// this way we make sure we support relocation // this way we make sure we support relocation
void* new_ptr = malloc(new_size); void* new_ptr = malloc(new_size);
memset(new_ptr, '#', new_size); // erase memset(new_ptr, '#', new_size); // erase
memcpy(new_ptr, ptr, std::min(new_size, new_size)); if (ptr) {
free(ptr); memcpy(new_ptr, ptr, std::min(new_size, new_size));
free(ptr);
}
return new_ptr; return new_ptr;
} }
}; };