如何检查数据是否仍在内存中

How to check if data is still in memory

假设我分配了一些任意大小的内存

void* p = malloc(WHATEVER_SIZE);

稍后我想检查(可能使用系统调用)该数据的哪些字节在物理内存中,以及需要发生多少页交换才能检索不在物理内存中的字节。有办法吗?

如果您使用的是 Linux 或类似系统,请尝试 mincore syscall. It gives you a bit vector representing, for a range of pages, which ones are physically resident at the time of the call. Of course this information could be outdated by the time you use it; it's inherently subject to a TOCTOU 比赛,除非页面被锁定。