# vtkGradientFilter segmentation fault

**URL:** https://discourse.vtk.org/t/vtkgradientfilter-segmentation-fault/10516
**Category:** Support
**Created:** [January 22, 2023, 7:49am UTC](https://discourse.vtk.org/t/vtkgradientfilter-segmentation-fault/10516 "2023-01-22T07:49:50Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![FanWang10](https://discourse.vtk.org/user_avatar/discourse.vtk.org/fanwang10/32/6394_2.png) [@FanWang10](https://discourse.vtk.org/u/FanWang10)
#### Post date: [January 22, 2023, 7:49am UTC](https://discourse.vtk.org/t/vtkgradientfilter-segmentation-fault/10516/1 "2023-01-22T07:49:50Z")

</div>

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](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\*)

```auto
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](https://discourse.vtk.org/uploads/short-url/xg8GIMbWpCpjdXKxpknhherjU5V.vtu) (1.0 KB)  
Thank you in advance!

---

<div class="post-metadata">

### Author: ![dgobbi](https://discourse.vtk.org/user_avatar/discourse.vtk.org/dgobbi/32/18_2.png) [@dgobbi](https://discourse.vtk.org/u/dgobbi)
#### Post date: [January 22, 2023, 9:44pm UTC](https://discourse.vtk.org/t/vtkgradientfilter-segmentation-fault/10516/2 "2023-01-22T21:44:12Z")

</div>

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.
