mirror of
https://github.com/espressif/openthread.git
synced 2026-08-21 09:59:52 +00:00
[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:
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user