From 026e0e90592c42c89506356f7ae510938c100d49 Mon Sep 17 00:00:00 2001 From: Niels Dekker Date: Wed, 10 Dec 2025 17:03:55 +0100 Subject: [PATCH] BUG: Avoid copying uninitialized pixels in CastImageFilter For a regular output pixel type like `RGBPixel` and `itk::Vector`, the expression `OutputPixelType outputPixel{ *outputIt }` had undefined behavior, within `CastImageFilter::DynamicThreadedGenerateDataDispatched`, because at that point, the pixel pointed to by `outputIt` was typically still uninitialized. For such output pixel types, `outputPixel` should be declared as a reference (`OutputPixelType &`) instead. The original `OutputPixelType outputPixel{ *outputIt }` initialization is only OK when the output pixel type is a `VariableLengthVector`. --- .../ImageFilterBase/include/itkCastImageFilter.hxx | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/Modules/Filtering/ImageFilterBase/include/itkCastImageFilter.hxx b/Modules/Filtering/ImageFilterBase/include/itkCastImageFilter.hxx index 30106a29a57..2cb1edbca6c 100644 --- a/Modules/Filtering/ImageFilterBase/include/itkCastImageFilter.hxx +++ b/Modules/Filtering/ImageFilterBase/include/itkCastImageFilter.hxx @@ -21,6 +21,7 @@ #include "itkProgressReporter.h" #include "itkImageAlgorithm.h" #include "itkImageRegionRange.h" +#include "itkVariableLengthVector.h" namespace itk { @@ -156,12 +157,19 @@ CastImageFilter::DynamicThreadedGenerateDataDispatche while (inputIt != inputEnd) { const InputPixelType & inputPixel = *inputIt; - OutputPixelType outputPixel{ *outputIt }; + + using OutputPixelValueType = typename OutputPixelType::ValueType; + + constexpr bool isVariableLengthVector = std::is_same_v>; + + // If the output pixel type is a VariableLengthVector, it behaves as a "reference" to the internal data. Otherwise + // declare outputPixel as a reference, `OutputPixelType &`, to allow it to access the internal buffer directly. + std::conditional_t outputPixel{ *outputIt }; + for (unsigned int k = 0; k < componentsPerPixel; ++k) { - outputPixel[k] = static_cast(inputPixel[k]); + outputPixel[k] = static_cast(inputPixel[k]); } - *outputIt = outputPixel; ++inputIt; ++outputIt; }