[vtkusers] Potential bug in use of vtkDataArray class and derivatives

Jason Griese jason at simbiosys.ca
Tue Apr 24 10:42:26 EDT 2001


While debugging some source code for my company, the program failed when the
following actions were performed:

    create vtkDataArray newPts
    ...
    fill newPts with data
    ...
    loop while there is more data to process and we won't exceed the bounds
of the array
            int arrayPointer =
ewPts->InsertNextPoint( newPts->GetPoint(var) )

Which means we are picking members of the array and inserting them at the
end of the array.the program failed because InsertNextPoint() calls
InsertTuple(*tuple) in the implementing class (in this case vtkFloatArray).
In InsertTuple WritePointer() is called, which resizes the array if the
array is full. This results in the original array being deleted. Only after
WritePointer is called does the function copy the data from tuple to the
array. If WritePointer resized the array, then tuple now points to
deallocated memory. Now although this is dangerous, it usually works, unless
the OS decides to reclaim the memory. When that happens, the program fails
completely. The obvious solution is to copy the contents of memory pointed
to by tuple/newPts->GetPoint(var) to another memory location, call
WritePointer(), and then copy the data into the array from the new memory
location. Due to safety concerns, I had to implement the solution in the
InsertTuple() function. But I'm sure a more efficient solution exists. While
this isn't really a bug with VTK (as this is a pretty singular problem), I
just thought I'd put out a warning in case anyone else had similar ideas for
using vtkDataArray.

Here is my modified code.

void vtkFloatArray::InsertTuple(const int i, const float * tuple)
{
  float *ary = new float[NumberOfComponents];
  for( int k = 0; k < this->NumberOfComponents; ++k)
  {
   ary[k] = tuple[k];
  }

  float *t =
this->WritePointer(i*this->NumberOfComponents,this->NumberOfComponents);
  for (int j=0; j<this->NumberOfComponents; j++)
  {
    *t++ = ary[j];//*tuple++;
  }
  delete[] ary;
}


Jason Griese





More information about the vtkusers mailing list