title: GDI+: unhandled exception when drawing bitmap
body: <p>What I am doing is reading greyscale jpeg using turbojpeg, creating Gdiplus::Bitmap using its data and trying to draw it using Gdiplus::Graphics. Everything is fine up to the point where i try to draw the image - I get <code>Unhandled exception at 0x74123193 in program.exe: 0xC0000005: Access violation reading location 0x04ac7848.</code> Bitmap is apparently created properly - <code>Bitmap::lastResult == Ok</code>. My code looks like this:</p>
  
  <pre><code>// Initialize GDI+.
  Gdiplus::GdiplusStartup(&amp;gdiplusToken, &amp;gdiplusStartupInput, NULL);
  
  // creating program window
  
  Graphics = new Gdiplus::Graphics(GetDC(hwnd));
  Graphics-&gt;SetCompositingMode( Gdiplus::CompositingModeSourceCopy );
  Graphics-&gt;SetCompositingQuality( Gdiplus::CompositingQualityHighSpeed );
  Graphics-&gt;SetPixelOffsetMode( Gdiplus::PixelOffsetModeNone );
  Graphics-&gt;SetSmoothingMode( Gdiplus::SmoothingModeNone );
  Graphics-&gt;SetInterpolationMode( Gdiplus::InterpolationModeDefault );
  
  // loading jpeg using turbojpeg
  std::vector&lt;unsigned char&gt; data;
  
  int width, 
      height;
  
  std::ifstream ifs(filename.c_str(), std::ios::in | std::ios::binary);
  
  long begin,end;
  begin = (long)ifs.tellg();
  ifs.seekg (0, std::ios::end);
  end = (long)ifs.tellg();
  long size = end - begin;
  ifs.seekg(0);
  
  std::vector&lt;char&gt; jpegdata(size);
  unsigned char* dataptr = reinterpret_cast&lt;unsigned char*&gt;(&amp;jpegdata[0]);
  ifs.read(&amp;jpegdata[0], jpegdata.size());
  tjhandle handle = tjInitDecompress();
  tjDecompressHeader(handle, dataptr, jpegdata.size(), &amp;width, &amp;height);
  data.resize(width * height);
  tjDecompress2(handle, dataptr, jpegdata.size(), &amp;data[0], width, width, height, TJPF_GRAY, 0);
  tjDestroy(handle);
  
  // creating Gdiplus::Bitmap
  Gdiplus::Bitmap *bitmap = new Gdiplus::Bitmap(width, 
                                  height, 
                                  width * 8, 
                                  PixelFormat8bppIndexed, 
                                  (BYTE*)&amp;data[0]);
  
  // drawing bitmap
  Graphics-&gt;DrawImage(bitmap, 0, 0);
  </code></pre>
  
  <p>The exception is thrown at</p>
  
  <pre><code>Graphics-&gt;DrawImage(bitmap, 0, 0);
  </code></pre>
  
  <p>What is the reason to this behavior? What am I doing wrong?</p>
  
  <p><code>edit</code>  </p>
  
  <p>Setting the correct stride as user1837009 suggested fixed the exception.</p>
  
  <p>There's a reason I use this particular constructor - I need to have the image data as raw as possible, greyscale, 8 bits per pixel to do some transformations. And I'm fairly certain that's what I have in <code>data</code> variable after calling <code>tjDecompress2</code>. Unfortunatelly, it seems there's no 8 bit greyscale pixel format supported, only PixelFormat16bppGrayScale, which is 16 bits. Any ideas on how to go around this?</p>