释放内存错误?

时间:2014-12-19 15:12:18

标签: c++ memory free allocation delete-operator

我需要释放bitpointer,因为这个函数被执行多次并且内存使用量增长的原因我不明白并且在达到22mb ram使用后它崩溃了。如果我试图删除bitpointer这样delete []bitpointerfree(bitpointer)我收到访问冲突错误。但是我不明白为什么,因为函数不应该再使用指针而且设置了新的红蓝绿色值..

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
}

2 个答案:

答案 0 :(得分:2)

在SelectObject中,保存返回的值:HGDIOBJ save = SelectObject(hdcTemp, hBitmap2);

然后在ReleaseDC之前删除DIB DeleteObject( SelectObject(hdcTemp, save) );

否则,您创建位图并且不要删除它们。

答案 1 :(得分:1)

如果你看到documentation,那么你会发现你不应该为bitPointer分配内存,CreateDIBSection会为你做这件事。您需要使用DeleteObject释放hBitmap2

发生崩溃是因为bitPointer youi释放的值不是您分配的值。 (并且你分配的内存被泄露了。)