Why does HeapFree() not working as it should?

530 views Asked by At

I created implementation in MVS without using CRT. I use HeapAlloc() and HeapFree() for allocating memory. My example should work without memory leak.
Here is my code:

LPCSTR byte2ch(BYTE* data, int size) {
    char* datas = (char*)HeapAlloc(GetProcessHeap(), NULL, size);
    LPCSTR temp = (reinterpret_cast<char const*>(data));
    for (int i = 0; i < size; i++) {
        datas[i] = temp[i];
    }
    LPSTR tempo = datas;
    HeapFree(GetProcessHeap(), NULL, (LPVOID)&size);
    return tempo;
}

int EntryPoint()
{
    BYTE* buffer = 0;

    HANDLE hFile;
    DWORD dwBytesRead, dwBytesWritten, dwPos;

    if (hFile = CreateFileW(L"MinerFinder.exe", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_ALWAYS, 0, NULL))
    {
        LARGE_INTEGER size;
        GetFileSizeEx(hFile, &size);

        buffer = (BYTE*)HeapAlloc(GetProcessHeap(), NULL, size.QuadPart);
        ReadFile(hFile, buffer, size.QuadPart, &dwBytesRead, NULL);

        MessageBoxA(NULL, byte2ch(buffer, size.QuadPart), NULL, SW_SHOW);
        HeapFree(GetProcessHeap(), NULL, (LPVOID)&size.QuadPart);
        MessageBoxA(NULL, "", NULL, SW_SHOW); // there I can see, that memory is leaking...
        CloseHandle(hFile);
    }

    ExitProcess(0);
}  

Where is my mistake?

EDIT 1:

LPCSTR byte2ch(BYTE* data, int size) {
        char* datas = (char*)HeapAlloc(GetProcessHeap(), NULL, size);
        LPCSTR temp = (reinterpret_cast<char const*>(data));
        for (int i = 0; i < size; i++) {
            datas[i] = temp[i];
        }
        LPSTR tempo = datas;
        HeapFree(GetProcessHeap(), NULL, datas);
        return tempo;
    }

there when I HeapFree() program suddenly crashes. What?

1

There are 1 answers

2
Olaf Dietsche On

Looking at HeapFree

BOOL HeapFree( HANDLE hHeap, DWORD dwFlags, _Frees_ptr_opt_ LPVOID lpMem );

lpMem

A pointer to the memory block to be freed. This pointer is returned by the HeapAlloc or HeapReAlloc function. If this pointer is NULL, the behavior is undefined.


In the code

HeapFree(GetProcessHeap(), NULL, (LPVOID)&size);
HeapFree(GetProcessHeap(), NULL, (LPVOID)&size.QuadPart);

You don't give an allocated pointer to HeapFree, but a pointer to the address of some unrelated (non-heap) memory.


The proper call would be

HeapFree(GetProcessHeap(), NULL, datas);

or

HeapFree(GetProcessHeap(), NULL, buffer);