Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,885 questions

51,811 answers

573 users

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

1 Answer

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

int main() {
    SIZE_T size = 1024;  // allocate 1 KB

    // Allocate memory
    void* mem = VirtualAlloc(
        nullptr,            // let Windows choose the address
        size,               // number of bytes
        MEM_RESERVE | MEM_COMMIT,
        PAGE_READWRITE      // memory protection
    );

    if (!mem) {
        std::cerr << "VirtualAlloc failed: " << GetLastError() << "\n";
        return 1;
    }

    std::cout << "Allocated at: " << mem << "\n";

    // Use the memory
    char* buffer = static_cast<char*>(mem);
    strcpy_s(buffer, size, "VirtualAlloc is a low-level Windows API function used to allocate memory");

    std::cout << buffer << "\n";

    // Free the memory
    BOOL ok = VirtualFree(mem, 0, MEM_RELEASE);
    if (!ok) {
        std::cerr << "VirtualFree failed: " << GetLastError() << "\n";
    }

    return 0;
}



/*
run:

Allocated at: 000002455A430000
VirtualAlloc is a low-level Windows API function used to allocate memory

*/

 



answered 3 hours ago by avibootz

Related questions

...