[toc]

使用C语言在windows分配其他程序的内存空间

1. C语言程序中使用malloc分配内存空间

1
2
3
4
5
6
7
8
9
#include <windows.h>
#include <stdio.h>


int main(int argc, char* argv[])
{
DWORD* lpBaseAddr = malloc(sizeof(DWORD));
return 0;
}

2.Windows使用VirtualAllocEx给其他进程分配空间

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <windows.h>
#include <stdio.h>

int main(int argc, char* argv[])
{
DWORD dwProcessId = 85064;
DWORD size=0xFFF;
HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwProcessId);
LPVOID lpAddress = VirtualAllocEx(hProcess, NULL, size, MEM_COMMIT | MEM_RESERVE,
PAGE_EXECUTE_READWRITE);
BOOL state=VirtualFreeEx(hProcess, (LPVOID)lpAddress, 0, MEM_RELEASE);
if (state != TRUE)return GetLastError();
CloseHandle(hProcess);
return 0;
}

3.C语言使用VirtualAllocEx在本进程中分配内存空间

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <windows.h>
#include <stdio.h>

const int c_Var = 0x400000;

int main(int argc, char* argv[])
{
DWORD size = 0xFFF;
LPVOID lpAddress = VirtualAllocEx(-1, NULL, size, MEM_COMMIT | MEM_RESERVE,
PAGE_EXECUTE_READWRITE);
if (NULL == lpAddress)return 0;
VirtualFreeEx(-1, lpAddress, 0, MEM_RELEASE);
printf("0x%p\n", lpAddress);
return 0;
}

4.使用C语言在本进程中给指定的首地址分配内存空间

x86项目中将随机基地址关闭,此次程序中0x420000是可读可写可执行的,VirtualAllocEx分配地址时需要找一片可读可写可执行的内存区域

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <windows.h>
#include <stdio.h>

const int c_Var = 0x400000;

int main(int argc, char* argv[])
{
DWORD size = 0xFFF;
DWORD baseAddr = 0x420000;
LPVOID lpAddress = VirtualAllocEx(-1, baseAddr, size, MEM_COMMIT | MEM_RESERVE,
PAGE_EXECUTE_READWRITE);
if (NULL == lpAddress)return 0;
VirtualFreeEx(-1, lpAddress, 0, MEM_RELEASE);
printf("0x%p\n", lpAddress);
return 0;
}