Search code examples
c++visual-c++gdi

CreateDibSection throws Access Violation Exception


I am trying to create a DIBSection to be able to render pixels faster, because SetPixel is too slow. Now, I am trying to create it like so:

void** imagePointer = NULL;
DWORD mask888[] = { 0xFF0000, 0x00FF00, 0x0000FF };

BITMAPINFO bitmapInfo = BITMAPINFO();
memset(&bitmapInfo, 0, sizeof(bitmapInfo));

memcpy(bitmapInfo.bmiColors, mask888, sizeof(mask888));

bitmapInfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bitmapInfo.bmiHeader.biWidth = LCD_WIDTH; // 160
bitmapInfo.bmiHeader.biHeight = LCD_HEIGHT; // 144
bitmapInfo.bmiHeader.biPlanes = 1;
bitmapInfo.bmiHeader.biBitCount = 32;
bitmapInfo.bmiHeader.biCompression = BI_RGB;

bitmap = CreateDIBSection(hdc, &bitmapInfo, DIB_RGB_COLORS, imagePointer, NULL, 0);

But what happens is, that I just get an Access Violation exception thrown when the CreateDIBSection Call is being executed.

The exception being thrown is the following:

Exception thrown at 0x76E69623 (gdi32.dll) in Emulation.exe: 0xC0000005: Access violation writing location 0x0000FF00.

Could you please tell me how to debug this or how to fix this problem?

Thank you very much in advance!


Solution

  • Whoops! You forgot to read the documentation.

    You pass a void** that doesn't point to anything, but that argument is:

    ppvBits [out] A pointer to a variable that receives a pointer to the location of the DIB bit values.

    Naturally, then, this null pointer is going to be dereferenced, causing undefined behaviour (and in your case an access violation).

    Instead, pass the address of imagePointer to ppvBits:

    BYTE* imagePointer = NULL; 
    ...
    bitmap = CreateDIBSection(hdc, &bitmapInfo, DIB_RGB_COLORS, (void**)&imagePointer, NULL, 0);