[vtkusers] Remark on vtkDataArrayTemplate<T>::Allocate(...)

Alain CORON alain.coron at lip.bhdc.jussieu.fr
Fri Aug 27 13:07:55 EDT 2004


Hello,

I use VTK 4.4 and I was looking at the following piece of code which can be
found in Common/vtkDataArrayTemplate.txx:

//----------------------------------------------------------------------------
// Allocate memory for this array. Delete old storage only if necessary.
template <class T>
int vtkDataArrayTemplate<T>::Allocate(vtkIdType sz, vtkIdType)
{
  if(sz > this->Size)
    {
    if(this->Array && !this->SaveUserArray)
      {
      delete [] this->Array;
      }

    this->Size = ( sz > 0 ? sz : 1);
    this->Array = new T[this->Size];
    if(!this->Array)
      {
      return 0;
      }
    this->SaveUserArray = 0;
    }

  this->MaxId = -1;

  return 1;
}

If the allocation fails, a bad_alloc exception is thrown or this->Array is
equal to 0 depending on your compiler.  Furthermore,

  - this->SaveUserArray might be different from 0;
  - this->MaxId is different from -1.
  - this->Size equals to sz and not 0.  A segmentation fault will occur soon.

If I am right, I suggest to replace this implementation by

//----------------------------------------------------------------------------
// Allocate memory for this array. Delete old storage only if necessary.
template <class T>
int vtkDataArrayTemplate<T>::Allocate(vtkIdType sz, vtkIdType)
{
  this->MaxID = -1;

  if(sz > this->Size)
    {
    if(this->Array && !this->SaveUserArray)
      {
      delete [] this->Array;
      }

    this->Array = 0;
    this->Size = 0;
    this->SaveUserArray = 0;

    int newSize = (sz > 0 ? sz : 1);
    this->Array = new T[newSize];
    if(!this->Array)
      {
      return 0;
      }
    this->Size = newSize;
    }

  return 1;
}

-- 
Alain CORON



More information about the vtkusers mailing list