[Insight-users] ImportImageFilter segfault

Dan Mueller dan.muel at gmail.com
Wed Jun 30 04:22:54 EDT 2010


Hi Miklos,

If you set LetFilterManageMemory=true when you import the buffer, the
import filter output image should take ownership of the buffer. I
think the issue is that you do not disconnect the output from the
filter (hence when the filter is destroyed, the image/buffer is
destroyed). Try something like this (DISCLAIMER: I have not compiled
or tested the below code):

    ImageType::Pointer createZeroImage() { // IMPORTANT: return smart pointer
        // Create importer
        ImporterType::Pointer importer = ImporterType::New();
        itk::Index<Dim> start;
        start.Fill(0);
        itk::Size<Dim>  size;
        size.Fill(10);
        itk::ImageRegion<Dim> region(start, size);
        importer->SetRegion(region);

        // Create buffer
        unsigned long pixelNo = region.GetNumberOfPixels();
        PixelType *ptr = new PixelType[pixelNo];
        for (unsigned i = 0; i < pixelNo; ++i)
            ptr[i] = 0;

        // Import the buffer, let the filter manage the memory
        importer->SetImportPointer(ptr, pixelNo, true);

        // Get imported image
        importer->Update();
        ImageType::Pointer image = importer->GetOutput();
        image->DisconnectPipeline(); // IMPORTANT: disconnect output

        // Clean up filter (output image should remain alive)
        importer = NULL;

        return image;
    }

Let us know if this works for you.

Cheers, Dan

On 30 June 2010 09:09, Miklos Espak <espakm at gmail.com> wrote:
> Hi,
>
> I created a filter for reading certain kind of images. It extends
> ImportImageFilter. It imports the image well, but I can use the output
> image as long as the importer is alive.
>
> The buffer with the raw image is set by the SetImportPointer member
> function. Its last bool argument decides if the filter is responsible
> for deallocating the buffer when it dies or not. If I set it to true,
> its destructor frees the buffer and accessing the pixels of the output
> image causes segfault. If it's false, I get memory leak. (I don't have
> a pointer to the buffer from outside of the filter itself.)
>
> I find this behaviour unusual. E.g. the output of an ImageFileReader
> can be used freely even the reader dies, and I guess this is the case
> with other input filters as well.
>
> Is there a way to delegate the responsibility of freeing the buffer to
> the output image? Is it intentional that this is not the default
> behaviour of ImportImageFilter?
>
> I attached a code that demonstrates the problem. Sorry for cppunit.
>
> Thanks,
> Miklos


More information about the Insight-users mailing list