本文介绍了释放内存错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要释放 bitpointer ,因为该函数已多次执行并且内存使用量由于我不了解的原因而增长,并且在达到22mb的ram使用率时崩溃.尝试删除 bitpointer ,例如 delete [] bitpointer free(bitpointer),我遇到访问冲突错误.但是我不明白为什么,因为该函数不再使用指针,并且设置了新的红色,蓝色,绿色值.

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
}

推荐答案

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

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

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

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

否则,您将创建位图而不删除它们.

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

这篇关于释放内存错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-07 08:38