c - 释放的内存不会导致页面错误

标签 c windows winapi virtual-memory

在为进程保留和提交虚拟内存的实验中,我使用 VirtualAlloc 分配了 64K 字节的内存,memcpy 将测试字符串放入其中,printf 像一个字符串一样,使用 VirtualFreeMEM_RELEASE 标志释放内存,然后再次 printf 。由于某种原因,没有触发页面错误。这是为什么?

#include <stdio.h>
#include <windows.h>

INT main(DWORD argc, LPSTR argv[]) {
    SYSTEM_INFO info;
    DWORD dwPageSize;
    DWORD dwMemSize;
    LPVOID lpvMem;

    GetSystemInfo(&info);
    dwPageSize = info.dwPageSize;
    dwMemSize = 16 * dwPageSize;

    lpvMem = VirtualAlloc((LPVOID) 0x00F00000, dwMemSize, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
    if (!lpvMem) {
        printf("Error allocating virtual memory\n");
        return 1;
    }

    printf("lpvMem = 0x%08X\n", (UINT32) (UINT64) lpvMem);

    if (!memcpy(lpvMem, "I love foxes \\(^o^)/", 21)) {
        printf("Error copying memory (error code 0x%08X)\n", GetLastError());
        return 1;
    }

    printf("Before free: %s\n", (LPCSTR) lpvMem);
    VirtualFree(lpvMem, dwMemSize, MEM_RELEASE);
    printf("After free:  %s\n", (LPCSTR) lpvMem);

    fflush(stdout);

    return 0;
}

输出:

lpvPagedMemory = 0x00F00000
Before free: I love foxes \(^o^)/
After free:  I love foxes \(^o^)/

最佳答案

这一行:

VirtualFree(lpvMem, dwMemSize, MEM_RELEASE);

是一个错误。你没有检查什么 VirtualFree()返回,文档说:

dwSize [in]
...
If the dwFreeType parameter is MEM_RELEASE, this parameter must be 0 (zero). The function frees the entire region that is reserved in the initial allocation call to VirtualAlloc.

所以你需要改用这个:

VirtualFree(lpvMem, 0, MEM_RELEASE);

关于页面错误 - 它可以(而且必须)仅在 成功 调用 VirtualFree() 之后发生。

关于c - 释放的内存不会导致页面错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38576982/

相关文章:

c - 给定一个长字符串数组,如何有效地检查给定的子字符串对(给定字符串)是否最多相差一个字符?

python - 时间跟踪软件如何找到应用程序的屏幕时间?

javascript - 使用 Windows PowerShell 传递 Node.js 环境变量

java - 如何使用显示器的输出作为程序的输入?

c++ - 插入加密U盘后,如何使用WMI找到 'launcher'逻辑盘?

c++ - 比较常规选择和准备选择性能

c - 修复 K&R 书中第 6.5 章示例中的内存泄漏(自引用结构)

c++ - 线程设计和设计以及在 C++ Win32 中从另一个线程中调用一个函数

c++ - 使用 Winapi 获取当前位置

c - 使用回溯的子集