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,890 questions

51,820 answers

573 users

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

1 Answer

0 votes
#include <windows.h>
#include <stdio.h>
#include <string.h>

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

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

    if (mem == NULL) {
        printf("VirtualAlloc failed: %lu\n", GetLastError());
        return 1;
    }

    printf("Allocated at: %p\n", mem);

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

    printf("%s\n", buffer);

    // Free the memory
    if (!VirtualFree(mem, 0, MEM_RELEASE)) {
        printf("VirtualFree failed: %lu\n", GetLastError());
    }

    return 0;
}




/*
run:

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

*/

 



answered 5 hours ago by avibootz

Related questions

...