Fix crash when ArrayList runs out of memory ()

The allocation size was still updated to the bigger size even if memory allocation failed. Trying to write to the supposedly available new space would overflow the heap and crash. Fixes 
This commit is contained in:
peace-maker 2020-04-30 18:59:54 +02:00 committed by GitHub
parent adcc0efda6
commit 5597fc56d3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -35,6 +35,7 @@
#include <stdlib.h>
#include <string.h>
#include <ICellArray.h>
#include <amtl/am-bits.h>
extern HandleType_t htCellArray;
@ -214,30 +215,34 @@ private:
{
return true;
}
size_t newAllocSize = m_AllocSize;
/* Set a base allocation size of 8 items */
if (!m_AllocSize)
if (!newAllocSize)
{
m_AllocSize = 8;
newAllocSize = 8;
}
if (!ke::IsUintPtrAddSafe(m_Size, count))
{
return false;
}
/* If it's not enough, keep doubling */
while (m_Size + count > m_AllocSize)
while (m_Size + count > newAllocSize)
{
m_AllocSize *= 2;
}
/* finally, allocate the new block */
if (m_Data)
{
cell_t *data = static_cast<cell_t*>(realloc(m_Data, sizeof(cell_t) * m_BlockSize * m_AllocSize));
if (!data) // allocation failure
if (!ke::IsUintPtrMultiplySafe(newAllocSize, 2))
{
return false;
}
m_Data = data;
} else {
m_Data = static_cast<cell_t*>(malloc(sizeof(cell_t) * m_BlockSize * m_AllocSize));
newAllocSize *= 2;
}
return (m_Data != nullptr);
/* finally, allocate the new block */
cell_t *data = static_cast<cell_t*>(realloc(m_Data, sizeof(cell_t) * m_BlockSize * newAllocSize));
/* Update state if allocation was successful */
if (data)
{
m_AllocSize = newAllocSize;
m_Data = data;
}
return (data != nullptr);
}
private:
cell_t *m_Data;