MCPcopy Create free account
hub / github.com/bytedance/sonic-cpp / Realloc

Method Realloc

include/sonic/allocator.h:383–416  ·  view source on GitHub ↗

Resizes a memory block (concept Allocator)

Source from the content-addressed store, hash-verified

381
382 //! Resizes a memory block (concept Allocator)
383 void* Realloc(void* originalPtr, size_t originalSize, size_t newSize) {
384 if (originalPtr == 0) return Malloc(newSize);
385
386 sonic_assert(shared_->refcount > 0);
387 if (newSize == 0) return nullptr;
388
389 originalSize = SONIC_ALIGN(originalSize);
390 newSize = SONIC_ALIGN(newSize);
391
392 // Do not shrink if new size is smaller than original
393 if (originalSize >= newSize) return originalPtr;
394
395 // Simply expand it if it is the last allocation and there is sufficient
396 // space
397 {
398 LOCK_GUARD;
399 if (originalPtr ==
400 GetChunkBuffer(shared_) + shared_->chunkHead->size - originalSize) {
401 size_t increment = static_cast<size_t>(newSize - originalSize);
402 if (shared_->chunkHead->size + increment <=
403 shared_->chunkHead->capacity) {
404 shared_->chunkHead->size += increment;
405 return originalPtr;
406 }
407 }
408 }
409
410 // Realloc process: allocate and copy memory, do not free original buffer.
411 if (void* newBuffer = Malloc(newSize)) {
412 if (originalSize) std::memcpy(newBuffer, originalPtr, originalSize);
413 return newBuffer;
414 }
415 return nullptr;
416 }
417
418 //! Frees a memory block (concept Allocator)
419 static void Free(void* ptr) noexcept { (void)ptr; } // Do nothing

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected