"Jigar Mehta" <jb*******@yahoo.co.in> wrote in message
news:%2****************@tk2msftngp13.phx.gbl...
Now here you can see that I am allocating some memory, after that I Save
the bitmap and then I want to free these memory.. All variables used are
global so, I will be able to free them up later.. But free() method gives me
error for lpbi_2 i.e. free(lpbi_2) gives runtime error (that abort dialog)...
Hi,
The only objects I see that need to be 'freed' are the HDC, and the HGLOBALs
hDib and hTemp. You obtain the HDC using CreateDC but then call ReleaseDC on
it. Rather you should use DeleteDC, I think. Otherwise, hDib seems local to
the function and seems properly managed to me. The hTemp is a return value,
so it is the caller's responsibility to call GlobalFree on it when it is
done. Nothing really seems to warrant a global or member variable (although
dwLen might be handy for future reference). You mention that using free is
failing -- as well it should. Nothing in the above needs to be passed to
free. Certainly not lpbi_2, that is not something that needs to deallocated
at all.
FWIW, I wrote the thing like so...
HANDLE AllocRoomForDIB(VOID)
{
DWORD dwLen = 1000;
HGLOBAL hDIB = GlobalAlloc(GHND,dwLen);
LPBITMAPINFOHEADER lpbi_2;
HGLOBAL hTemp;
// Check that DIB handle is valid
if (!hDIB)
return NULL;
lpbi_2 = (LPBITMAPINFOHEADER)GlobalLock(hDIB);
GlobalUnlock(hDIB);
dwLen *= 3000;
hTemp = GlobalReAlloc(hDIB,dwLen,0);
if (hTemp)
return hTemp;
else
{
// Else free memory block and return failure
OutputDebugString(_T("Freeing in ERROR\n"));
if ((BOOL)GlobalFree(hDIB))
OutputDebugString(_T("\tFAILURE to free\n"));
}
return NULL;
}
....and called it like so...
INT
WINAPI
_tWinMain(
HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpszCmdLine,
INT nCmdChow
)
{
INT i;
for (i = 0; i < 1000; i++)
{
HANDLE hRet = AllocRoomForDIB();
if (hRet)
{
OutputDebugString(_T("Freeing in CALLER\n"));
if ((BOOL)GlobalFree(hRet))
OutputDebugString(_T("\tFAILURE to free\n"));
}
Sleep(100);
}
return 0;
// Unused
hInstance;
hPrevInstance;
lpszCmdLine;
nCmdChow;
}
....and it never seemed to report either failure or error.
--
Jeff Partch [VC++ MVP]