[vtkusers] Access violation when using vtkPolyDataReader

David Cole david.cole at kitware.com
Fri Jul 29 12:56:06 EDT 2005


The original code in question...

assert(readers=(vtkPolyDataReader**)calloc(inputs,sizeof(vtkPolyDataReader*)));

...was attempting to allocate an array of pointers. You can use any 
method you want to allocate an array of pointers, even pointers to C++ 
objects. This line of code would be perfectly fine if it were not inside 
an assert. In fact, it would be perfectly fine to leave the assert if 
you split it into two lines like this:

readers=(vtkPolyDataReader**)calloc(inputs,sizeof(vtkPolyDataReader*));
assert(readers);

On the other hand, you can't (and your compiler *should* back me up on 
this one - let me know if there's a C++ compiler that doesn't throw an 
error if you try this...) allocate a vtkObject derived object on the 
stack or even on the heap directly with lower case "new." You must go 
through the VTK object's upper case "New" method to allocate one. The 
reason is that the default constructors of vtkObject derived objects are 
protected, and therefore inaccessible to all but subclasses and friends. 
Having an enforced factory method like VTK's upper case "New" allows us 
to do things like create the correct concrete subclass of 
vtkRenderWindow when you call vtkRenderWindow::New. It also makes for 
easy reference counting.

When using VTK from C++ diretly, always allocate with upper case "New" 
and always deallocate with upper case "Delete."


Hope this helps,
David


tom fogal wrote:

> <42E947AC.3080209 at nmr.mgh.harvard.edu>Sean McInerney writes:
><snip>
>  
>
>>3. Why not use C++'s operator new? It throws an exception and aborts by
>>default if an allocation fails.
>>    
>>
>
>good call.
>
>  
>
>>David Cole wrote:
>>    
>>
><snip>
>  
>
>>>>assert(readers=(vtkPolyDataReader**)calloc(inputs,sizeof(vtkPolyDataReader*
>>>>        
>>>>
>>)));
>>    
>>
>
>You cannot use C memory allocation routines to get memory for C++
>objects. If you want an array of vtkPolyDataReaders, you want to do
>something like this:
>
>readers = new vtkPolyDataReader[number_of_elements_in_array];
>
>I'm not sure VTK's allocation model (via ::New()) allows this. You
>could probably declare the 'readers' variable as an array in the
>function, and then allocate. For example:
>
>void somefunc() {
>	int i;
>	vtkPolyDataReaders *readers[10];
>
>	for(i=0; i < 10; ++i) { readers[i] = vtkPolyDataReader::New(); }
>}
>
>HTH,
>
>-tom
>_______________________________________________
>This is the private VTK discussion list. 
>Please keep messages on-topic. Check the FAQ at: http://www.vtk.org/Wiki/VTK_FAQ
>Follow this link to subscribe/unsubscribe:
>http://www.vtk.org/mailman/listinfo/vtkusers
>
>
>  
>




More information about the vtkusers mailing list