Different behavior between Release and Debug for treating uninitialized memory

Hi All,

I am confused by different behavior between Release and Debug configuration for treating uninitialized memory within itk image. My development environment is shown as follows:
OS: Windows 7 64 bit SP1
IDE: Visual Studio 2012
ITK: itk-4.8.0

Then, the experiment I made is described as follows:

  1. Read an image using itkImageFileReader
  2. Take size, spacing, origin, region from input image and use those components to create a test image.
  3. Allocate the test image without initialization.
  4. Write out the test image using itkImageFileWriter

In case of Debug mode, the output image is full of uninitialized memory which just match my expectation. However, in case of Release mode, half of output image was initialized by zero, and the rest parts stay uninitialized. Seems compiler attempts to initialize those uninitialized pixel when run Release, but got stop by some unknown reason.

Can anyone explain the rule of automatic memory initialization when run Release mode in visual studio compiler?

I think your expectation of “uninitialized” memory may not be correct. When you say: “In case of Debug mode, the output image is full of uninitialized memory”, I am not sure what you mean. Is it random numbers? Is it all zeroes?

Uninitialized memory is just that, uninitialized and filled with whatever may be left over from the last usage. Given a programs deterministic usage of memory, and deterministic algorithm for memory allocation the unitized value may be deterministic too. However, with a different execution it could be different, and it will certainly be different on a different OS system. In debug mode, compilers frequently fill newly allocate memory with values, or pad the boundary of the allocation to help detect out of bound access/writing etc.

You likely want to use itk::Image::FillBuffer so as to not use uninitilzied memory.

1 Like

You can also just use the image->Allocate(true); to have the memory initialized to all zeroes.

1 Like

Hi All,

Sorry for late reply. I just came back from my new year vacation.

Thank you all for reply my question. However, I have to say I know both FillBuffer and Allocate(true) methods, but these are not the thing I tried to ask. Please see following images, they are generated by the same source code but different configuration.
Release: half of output image was initialized by zero
Release
Debug: full of uninitialized memory
Debug
The thing I am trying to dig is why there are different behaviors when compiler encounters uninitialized memory with release and debug mode. Is this situation has been expected in visual studio C++?

Because you are invoking undefined behaviour:

http://blog.llvm.org/2011/05/what-every-c-programmer-should-know.html

3 Likes