hen i am creating a smart pointer globally and allocating the memory to it.
In debug mode “it crashes”. While when the same code is run in release mode
it seems to work fine. Can some one help me out, why is it so ?
Please find the below code:
typedef signed short PixelType;
typedef itk::Image< PixelType, 3>ImageType;
typedef itk::ImageSeriesReader< ImageType >ReaderType;
ReaderType:: Pointer reader= ReaderType::New();
void ImageRead()
{
// using pointer reader here.
// which is allocated memory at global level
}
This is simple cpp file containing function to read dicom. In which the dicomReader pointer is made global. This code runs in release mode and crashes in debug mode. While debugging i found that i crashes in itkImageSource class under template< typename TOutputImage > ImageSource< TOutputImage >::ImageSource().
The program you provided crashed in both Debug and Release mode for me. The problem seems to be having the reader as a global variable. With global variables, the order of initialization between different translation units is not predetermined, so it might get to be initialized before ITK’s global variables. Here is the code which does work for me:
Thanks for your kind explanation. In that case reader pointer scope will be bound to ParseDicom function. If i want to use the reader pointer in another function then it will be problem. Suppose i have another function which updates the origin matrix using reader origin, as the reader pointer will not be available to me in this function.
The following code seems to work for me. But i am not sure further how this will behave inside ITK. Please let me know if it is fine to do as follows:
ReaderType::Pointer dicomReader ; ////= ReaderType::New(); // this is done inside function
// in this case needs to make sure ParseDicom is called first, before UpdateOrigin
void ParseDicom(const string &dicomDirectory)
{
dicomReader = ReaderType::New();
That would work. However that would recreate the reader each time, despite having a global pointer to it. A much more common approach is to save the image, e.g.:
This is more common than a global reader, but not correct. The “correct” way would be to avoid global variables completely, and pass parameters to and from functions: