Skip to content

const-qualified images can be modified via itk::ImageRegionIterator<const ImageType> #7003

Closed

Description

@mymonin

Description

Any user provided with a read-only image:

 auto constImage = ImageType::ConstPointer{ /* ... */ };

can instantiate the following ITK iterator:

auto it = itk::ImageRegionIterator<const ImageType>{ constImage, constImage->GetBufferedRegion() };

which allows them to write over the image:

it.Set( /* ... */ );

This makes it easy for the user to (accidentally or not) bypass const-correctness through the iterator API.

Issue #6102 identifies similar symptoms, however, the backdoor showcased here is not particularly unusual. Indeed, this demonstrates that all non-const ITK iterators do actually provide a constructor with a const ImageType * parameter.

Steps to Reproduce

Append the following test to itkImageIteratorsGTest.cxx:

TEST(ImageIterators, ConstCorrectness)
{
  using ImageType = itk::Image<int, 2>;

  // Return a constant 1-pixel image whose value is 1.
  auto makeConstImage = []() -> ImageType::ConstPointer {
    const auto image = ImageType::New();
    image->SetRegions(ImageType::SizeType::Filled(1));
    image->Allocate();
    image->FillBuffer(1);
    return image;
  };

  auto constImage = makeConstImage();

  // Non-const iterator instantiated with a const image
  auto it = itk::ImageRegionIterator<const ImageType>{ constImage, constImage->GetBufferedRegion() };

  EXPECT_EQ(it.Get(), 1);

  // No problem writing to the const image
  it.Set(2);

  EXPECT_EQ(it.Get(), 2);
}

Expected behavior

The test should not compile

Actual behavior

The test compiles and passes

Reproducibility

100% reproducible on the current version of master.

Activity

  1. added
    type:Bug
    on Oct 24, 2026
  2. hjmjohnson commented on Nov 1, 2026

    @hjmjohnson
    Member

    Thanks for reporting this, @mymonin. #7065 fixes it: ImageRegionIterator<const ImageType> and every other iterator over a const image no longer have Set() or a writable Value(), and a compile-time test checks this case. This issue is now an acceptance criterion of #6141, and both will close when #7065 merges.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    type:Bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions