Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.7k views
in Technique[技术] by (71.8m points)

c++ - Freeing memory error?

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
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...