[heap-data] use allocate-first pattern in UpdateBuffer() (#12794)

Heap::Data::UpdateBuffer() freed the existing buffer before
attempting to allocate a new one. If the allocation failed,
mData retained a dangling pointer to the already-freed buffer.
A subsequent Free() call (from the destructor or an error path)
would then free the same pointer again, causing a double-free.

This changes UpdateBuffer() to use the allocate-first pattern
(consistent with Heap::String::Set): the new buffer is allocated
first, and the old buffer is freed only after a successful
allocation. On allocation failure, the old buffer is preserved
and no dangling pointer is created.

Signed-off-by: Oblivionsage <[email protected]>
This commit is contained in:
Oblivionsage
2026-04-03 11:17:54 -05:00
committed by GitHub
parent dab83c966b
commit c7b922cd99
+2 -2
View File
@@ -120,10 +120,9 @@ Error Data::UpdateBuffer(uint16_t aNewLength)
VerifyOrExit(aNewLength != mData.GetLength());
Heap::Free(mData.GetBytes());
if (aNewLength == 0)
{
Heap::Free(mData.GetBytes());
mData.Init(nullptr, 0);
}
else
@@ -131,6 +130,7 @@ Error Data::UpdateBuffer(uint16_t aNewLength)
uint8_t *newBuffer = static_cast<uint8_t *>(Heap::CAlloc(aNewLength, sizeof(uint8_t)));
VerifyOrExit(newBuffer != nullptr, error = kErrorNoBufs);
Heap::Free(mData.GetBytes());
mData.Init(newBuffer, aNewLength);
}