前言
直接申请内存的目的是为了实现动态内存管理、灵活存储数据、控制内存生命周期、优化性能等。在 Windows 编程中,合理地使用动态内存可以提高程序的灵活性和效率
- 使用
malloc与free来进行内存申请与释放
#include <windows.h>
#include <iostream>
int main() {
// 申请内存
int* array = (int*)malloc(10 * sizeof(int)); // 动态分配10个整数的内存
if (array == NULL) {
std::cerr << "Memory allocation failed!" << std::endl;
return 1;
}
// 使用申请的内存
for (int i = 0; i < 10; ++i) {
array[i] = i * 10; // 初始化数组
std::cout << "array[" << i << "] = " << array[i] << std::endl;
}
// 释放内存
free(array); // 释放申请的内存
return 0;
}
VirtualAlloc和VirtualFree
#include <windows.h>
#include <iostream>
int main() {
// 分配 1MB 的内存
SIZE_T size = 1024 * 1024; // 1MB
LPVOID pMemory = VirtualAlloc(NULL, size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
if (pMemory == NULL) {
std::cerr << "VirtualAlloc failed!" << std::endl;
return 1;
}
// 使用申请的内存
int* array = static_cast<int*>(pMemory);
for (int i = 0; i < 256 * 1024; ++i) { // 256KB 整数
array[i] = i;
}
// 输出一些数据
std::cout << "array[0] = " << array[0] << std::endl;
std::cout << "array[255] = " << array[255] << std::endl;
// 释放内存
if (!VirtualFree(pMemory, 0, MEM_RELEASE)) {
std::cerr << "VirtualFree failed!" << std::endl;
return 1;
}
return 0;
}
HeapAlloc和HeapFree
#include <windows.h>
#include <iostream>
int main() {
// 创建一个堆
HANDLE hHeap = HeapCreate(HEAP_GENERATE_EXCEPTIONS, 0, 0);
if (hHeap == NULL) {
std::cerr << "HeapCreate failed!" << std::endl;
return 1;
}
// 从堆中分配内存
int* pMemory = (int*)HeapAlloc(hHeap, HEAP_ZERO_MEMORY, sizeof(int) * 10);
if (pMemory == NULL) {
std::cerr << "HeapAlloc failed!" << std::endl;
HeapDestroy(hHeap);
return 1;
}
// 使用申请的内存
for (int i = 0; i < 10; ++i) {
pMemory[i] = i * 10;
std::cout << "pMemory[" << i << "] = " << pMemory[i] << std::endl;
}
// 释放内存
HeapFree(hHeap, 0, pMemory);
// 销毁堆
HeapDestroy(hHeap);
return 0;
}
- 使用
CreateFileMapping创建共享的文件映射
#include <windows.h>
#include <iostream>
int main() {
// 创建文件映射
HANDLE hMapping = CreateFileMapping(
INVALID_HANDLE_VALUE, // 创建匿名映射
NULL, // 默认安全属性
PAGE_EXECUTE_READWRITE, // 可执行、可读、可写
0, // 高32位
0x1000, // 4096字节
L"KOPI" // 映射对象名称
);
if (hMapping == NULL) {
std::cerr << "CreateFileMapping failed: " << GetLastError() << std::endl;
return 1;
}
// 映射视图
LPVOID pView = MapViewOfFile(
hMapping, // 文件映射句柄
FILE_MAP_ALL_ACCESS, // 读写访问
0, // 文件偏移(高32位)
0, // 文件偏移(低32位)
0 // 映射整个文件
);
if (pView == NULL) {
std::cerr << "MapViewOfFile failed: " << GetLastError() << std::endl;
CloseHandle(hMapping);
return 1;
}
// 使用映射的视图
int* data = static_cast<int*>(pView);
*data = 42; // 写入数据
// 读取数据
std::cout << "Data written to shared memory: " << *data << std::endl;
// 解除映射
UnmapViewOfFile(pView);
// 关闭映射句柄
CloseHandle(hMapping);
return 0;
}
一般跨进程操作,使用第2种,第三种来实现跨进程函数调用注入.