Freeing memory error?

吃可爱长大的小学妹 提交于 2020-12-23 11:51:29

问题


I need to free the bitpointer, because this function is executed multiple times and memory usage is growing for a reason I don't understand and it crashes after reaching 22mb of ram usage.. If I try to delete the bitpointer like this delete []bitpointer or free(bitpointer)I get access violation error. But I don't understand why, because the function shouldn't use the pointer any more and the new red blue green values are set..

void Get_Color(int x,int y,int w,int h,int &red,int &green,int &blue,int action)
{
    HDC hdc, hdcTemp;
    RECT rect;
    BYTE*bitPointer=new BYTE[4*h*w];
    HWND Desktop = GetDesktopWindow();
    hdc = GetDC(Desktop);
    GetWindowRect(Desktop, &rect);
    hdcTemp = CreateCompatibleDC(hdc);
    BITMAPINFO bitmap;
    bitmap.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
    bitmap.bmiHeader.biWidth = w;
    bitmap.bmiHeader.biHeight = h;
    bitmap.bmiHeader.biPlanes = 1;
    bitmap.bmiHeader.biBitCount = 32;
    bitmap.bmiHeader.biCompression = BI_RGB;
    bitmap.bmiHeader.biSizeImage = 0;
    bitmap.bmiHeader.biClrUsed = 0;
    bitmap.bmiHeader.biClrImportant = 0;
    HBITMAP hBitmap2 = CreateDIBSection(hdcTemp, &bitmap, DIB_RGB_COLORS, (void**)(&bitPointer), NULL, NULL);
    SelectObject(hdcTemp, hBitmap2);
    BitBlt(hdcTemp, 0, 0, w, h, hdc, x, y, SRCCOPY);
    if(action==1)
    {
        for(int j=0;j<=w*h*4;j+=4)
        {
            red = bitPointer[j+2];
            green = bitPointer[j+1];
            blue = bitPointer[j];
            if(red<30 && green>190 && blue>190)
            {
                break;
            }
        }   
    }
    else
    {
        for(int j=0;j<=w*h*4;j+=4)
        {
            red = bitPointer[j+2];
            green = bitPointer[j+1];
            blue = bitPointer[j];
            break;

        }   
    }
    ///RELEASE
    ReleaseDC(NULL,hdc);
    ReleaseDC(NULL,hdcTemp);
    delete []bitPointer; ///Error
}

回答1:


If you read the documentation you'll see that you shouldn't be allocating memory for bitPointer, CreateDIBSection does that for you. You need to use DeleteObject to free hBitmap2.

The crash occurs because the value of bitPointer youi are freeing is not the one that you allocated. (And the memory you allocated is leaked.)




回答2:


In SelectObject, save the returned value: HGDIOBJ save = SelectObject(hdcTemp, hBitmap2);

Then before ReleaseDC, delete the DIB DeleteObject( SelectObject(hdcTemp, save) );

Otherwise, you create bitmaps and don't delete them.



来源:https://stackoverflow.com/questions/27568783/freeing-memory-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!