1
0
mirror of https://github.com/alliedmodders/metamod-source.git synced 2024-11-29 11:24:19 +01:00

fixed a subtle invalid memory access bug in CVector

--HG--
extra : convert_revision : svn%3Ac2935e3e-5518-0410-8daf-afa5dab7d4e3/trunk%40524
This commit is contained in:
David Anderson 2007-10-16 20:01:30 +00:00
parent e620cd5af4
commit a0f9d0898c

View File

@ -19,39 +19,58 @@ namespace SourceHook
// Vector
template <class T> class CVector
{
bool Grow()
bool Grow(size_t amount)
{
// automatic grow
size_t newSize = m_Size * 2;
if (newSize == 0)
newSize = 8; // a good init value
{
newSize = 8;
}
while (m_CurrentUsedSize + amount > newSize)
{
newSize *= 2;
}
T *newData = new T[newSize];
if (!newData)
return false;
if (m_Data)
{
for (size_t i=0; i<m_CurrentUsedSize; i++)
{
newData[i] = m_Data[i];
}
delete [] m_Data;
}
m_Data = newData;
m_Size = newSize;
return true;
}
bool GrowIfNeeded()
bool GrowIfNeeded(size_t amount)
{
if (m_CurrentUsedSize >= m_Size)
return Grow();
if (m_CurrentUsedSize + amount >= m_Size)
{
return Grow(amount);
}
else
{
return true;
}
}
bool ChangeSize(size_t size)
{
// change size
if (size == m_Size)
{
return true;
}
if (!size)
{
@ -65,19 +84,24 @@ template <class T> class CVector
}
T *newData = new T[size];
if (!newData)
return false;
if (m_Data)
{
size_t end = (m_CurrentUsedSize < size) ? (m_CurrentUsedSize) : size;
for (size_t i=0; i<end; i++)
{
newData[i] = m_Data[i];
}
delete [] m_Data;
}
m_Data = newData;
m_Size = size;
if (m_CurrentUsedSize > m_Size)
{
m_CurrentUsedSize = m_Size;
}
return true;
}
@ -85,7 +109,9 @@ template <class T> class CVector
void FreeMemIfPossible()
{
if (!m_Data)
{
return;
}
if (!m_CurrentUsedSize)
{
@ -95,11 +121,15 @@ template <class T> class CVector
size_t newSize = m_Size;
while (m_CurrentUsedSize <= newSize / 2)
{
newSize /= 2;
}
if (newSize != m_Size)
{
ChangeSize(newSize);
}
}
protected:
T *m_Data;
size_t m_Size;
@ -321,14 +351,13 @@ public:
bool push_back(const T & elem)
{
++m_CurrentUsedSize;
if (!GrowIfNeeded())
if (!GrowIfNeeded(1))
{
--m_CurrentUsedSize;
return false;
}
m_Data[m_CurrentUsedSize - 1] = elem;
m_Data[m_CurrentUsedSize++] = elem;
return true;
}
@ -433,13 +462,13 @@ public:
size_t ofs = where - begin();
++m_CurrentUsedSize;
if (!GrowIfNeeded())
if (!GrowIfNeeded(1))
{
--m_CurrentUsedSize;
return false;
}
++m_CurrentUsedSize;
where = begin() + ofs;
// Move subsequent entries