fix realloc when initial size was 0 (bug reported by Jens Mueller)

This commit is contained in:
Gael Guennebaud 2009-05-07 13:13:42 +00:00
parent 4f0af00e51
commit 6dffdca123

View File

@ -244,15 +244,23 @@ class SparseMatrix
float reallocRatio = 1; float reallocRatio = 1;
if (m_data.allocatedSize()<=m_data.size()) if (m_data.allocatedSize()<=m_data.size())
{ {
// we need to reallocate the data, to reduce multiple reallocations // if there is no preallocated memory, let's reserve a minimum of 32 elements
// we use a smart resize algorithm based on the current filling ratio if (m_data.size()==0)
// in addition, we use float to avoid integers overflows {
float nnzEstimate = float(m_outerIndex[outer])*float(m_outerSize)/float(outer+1); m_data.reserve(32);
reallocRatio = (nnzEstimate-float(m_data.size()))/float(m_data.size()); }
// furthermore we bound the realloc ratio to: else
// 1) reduce multiple minor realloc when the matrix is almost filled {
// 2) avoid to allocate too much memory when the matrix is almost empty // we need to reallocate the data, to reduce multiple reallocations
reallocRatio = std::min(std::max(reallocRatio,1.5f),8.f); // we use a smart resize algorithm based on the current filling ratio
// in addition, we use float to avoid integers overflows
float nnzEstimate = float(m_outerIndex[outer])*float(m_outerSize)/float(outer+1);
reallocRatio = (nnzEstimate-float(m_data.size()))/float(m_data.size());
// furthermore we bound the realloc ratio to:
// 1) reduce multiple minor realloc when the matrix is almost filled
// 2) avoid to allocate too much memory when the matrix is almost empty
reallocRatio = std::min(std::max(reallocRatio,1.5f),8.f);
}
} }
m_data.resize(m_data.size()+1,reallocRatio); m_data.resize(m_data.size()+1,reallocRatio);