vtkGradientFilter segmentation fault

Hello,
I am using to calculate the gradient of each vertex in an unstructured grid. I followed this example and made some changes: https://gitlab.kitware.com/vtk/vtk/-/blob/v9.2.0/Accelerators/Vtkm/Filters/Testing/Cxx/TestVTKMGradient.cxx
But my codes always gives me segmentation fault when i want to access the gradient data(with the type of vtkDoubleArray*)

int main()
{
    vtkNew<vtkXMLUnstructuredGridReader> reader;
    reader->SetFileName("testInput.vtu");
    reader->Update();

    vtkNew<vtkGradientFilter> gradientFilter;
    gradientFilter->SetInputConnection(reader->GetOutputPort());
    gradientFilter->SetInputScalars(vtkDataObject::FIELD_ASSOCIATION_POINTS, "scalars");
    gradientFilter->SetResultArrayName("gradient");

    gradientFilter->Update();

    vtkDoubleArray* gradientArray =
    vtkArrayDownCast<vtkDoubleArray>(vtkDataSet::SafeDownCast(gradientFilter->GetOutput())
                                       ->GetPointData()
                                       ->GetArray("gradient"));
    // seg fault here!
    gradientArray->GetNumberOfComponents();
}

testInput.vtu (1.0 KB)
Thank you in advance!

According to the documentation of vtkImageGradient, for the output,

data type will be either float or double

More specifically, the output data type will be float unless the input data type is double, long long, or unsigned long long.

A VTK down cast will return nullptr if the type is incorrect. The “safe” just means that it’s a dynamic cast, not a static cast. You still need to check for nullptr to make it truly safe.

1 Like