How to use the GlobalAlloc function using the Win32 API in C++

1 Answer

0 votes
#include <windows.h>
#include <iostream>

int main()
{
    SIZE_T size = 128;  // allocate 128 bytes

    // Allocates the specified number of bytes from the heap
    // Allocate movable memory (GMEM_MOVEABLE is required by some APIs)
    HGLOBAL hMem = GlobalAlloc(GMEM_MOVEABLE | GMEM_ZEROINIT, size);
    if (hMem == NULL) {
        std::cerr << "GlobalAlloc failed\n";
        return 1;
    }

    // Lock the memory to get a pointer
    void* pMem = GlobalLock(hMem);
    if (pMem == NULL) {
        std::cerr << "GlobalLock failed\n";
        GlobalFree(hMem);
        return 1;
    }

    // Use the memory
    strcpy_s((char*)pMem, size, "GlobalAlloc memory allocation");

    std::cout << "Stored in memory: " << (char*)pMem << std::endl;

    // Unlock the memory
    GlobalUnlock(hMem);

    // Free the memory
    if (GlobalFree(hMem) != NULL) {
        std::cerr << "GlobalFree failed\n";
        return 1;
    }

    return 0;
}



/*
run:

Stored in memory: GlobalAlloc memory allocation

*/

 



answered Feb 11 by avibootz
edited Feb 12 by avibootz

Related questions

...