跳至主要内容

19.私有内存的申请与释放

申请内存的两种方式

  • 通过VirtualAlloc/VirtualAllocEx申请的Private Memory
  • 通过CreateFileMapping映射的Mapped Memory
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <memoryapi.h>
#include <minwindef.h>
#include <stdio.h>
#include <synchapi.h>
#include <winnt.h>

int main(int argc, char *argv[]) {
LPVOID p = VirtualAlloc(
NULL, //要分配的内存区域的地址
0x1000*2, //分配的大小
MEM_COMMIT, //分配的类型 例如:MEM_RESERVE MEM_COMMIT
PAGE_READWRITE //该内存的初始保护属性
);
Sleep(5000);
VirtualFree(p, 0x1000*2, MEM_DECOMMIT);

return 0;
}

堆与栈

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

int main(int argc, char *argv[]) {
int x = 0x12345678;
int *y = (int*)malloc(sizeof(int)*128);
// new = malloc + 构造
printf("栈:%p\n",&x);
printf("堆:%p\n",y);
getchar();
//malloc->HeapAlloc->没有进内核
return 0;
}

关于本文

由 GuQing 撰写,采用 CC BY-NC 4.0 许可协议。