How to generate vtkImageData from mathematical function

Thank you for your example. But using your code I stillget the same crash:

double spacing[3] = { 0.1, 0.1, 0.1 };
int size[3] = { 201, 201, 201 };
double origin[3] = { -10.0, -10.0, -10.0 };

auto imageData = vtkSmartPointer<vtkImageData>::New();
imageData->SetDimensions(size);
imageData->SetSpacing(spacing);
imageData->SetOrigin(origin);
imageData->AllocateScalars(VTK_FLOAT, 1);

vtkFloatArray* scalars = vtkFloatArray::SafeDownCast(imageData->GetPointData()->GetScalars());
vtkImagePointIterator iter(imageData);

while (!iter.IsAtEnd())	{
	double point[3];
	iter.GetPosition(point);
	double value = point[0] * point[0] + point[1] * point[1] + point[2] * point[2];
	scalars->SetValue(iter.GetId(), value);
	iter.Next();
}
	
vtkNew<vtkMetaImageWriter> writer;
writer->SetInputData(imageData);
writer->SetFileName("data.mhd");
writer->Update();

Error stays exactly the same, even with your simplified function.