# VirtualAllocEx

VirtualAllocEx는 다른 프로세스 내에서 메모리를 할당하는 함수이며, 이 함수에 의해 할당된 메모리는 자동으로 0으로 초기화됩니다.

이 함수는 주로 인젝션 시 페이로드를 저장할 공간 확보에 사용됩니다.

```cpp
LPVOID VirtualAllocEx(
  [in]           HANDLE hProcess,
  [in, optional] LPVOID lpAddress,
  [in]           SIZE_T dwSize,
  [in]           DWORD  flAllocationType,
  [in]           DWORD  flProtect
);
```

| 인자               | 설명         | 보편적인 값                      |
| ---------------- | ---------- | --------------------------- |
| hProcess         | 대상 프로세스 핸들 |                             |
| lpAddress        | 할당할 주소     | NULL(OS가 자동 선택)             |
| dwSize           | 할당 크기      |                             |
| flAllocationType | 할당 타입      | `MEM_COMMIT \| MEM_RESERVE` |
| flProtect        | 메모리 보호 속성  | `PAGE_EXECUTE_READWRITE`    |

## Example

```cpp
#include <windows.h>
#include <tlhelp32.h>
#include <iostream>
using namespace std;

LPVOID allocRemoteMemory(HANDLE hProc, SIZE_T dataSize) {
    LPVOID exec = VirtualAllocEx(
        hProc, NULL, dataSize,
        MEM_COMMIT | MEM_RESERVE,
        PAGE_EXECUTE_READWRITE
    );
    if (!exec) {
        wcout << L"Failed to get Memory buffer" << endl;
    }
    return exec;
}

HANDLE openProcessByPid(DWORD processId) {
    HANDLE hProc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, processId);
    if (!hProc) {
        wcout << L"Failed to get Process handle" << endl;
    }
    return hProc;
}

int main() {
    int pid = 1234;
    SIZE_T 
    HANDLE hProc = openProcessByPid(pid);
    LPVOID exec = allocRemoteMemory(hProc, dataSize);
    CloseHandle(hProc);
    return 0;
}
```

## References

{% embed url="<https://learn.microsoft.com/ko-kr/windows/win32/api/memoryapi/nf-memoryapi-virtualallocex>" %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://www.pentestwiki.com/defense-evasion/windows-api/virtualallocex.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
