我想编写一个测试(gcc 4.7),在其中分配一页内存,该内存页位于我的进程不拥有的内存页的旁边,这样通过页面末尾的未对齐读取应该出现段错误.
这可能吗?我该怎么做?
最佳答案
您可以使用 mprotect使用 protection = PROT_NONE
使页面不可访问,例如
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
int main(void)
{
char * a = valloc(4096 * 2); // page-aligned memory allocation (two pages)
int status = mprotect(&a[4096], 4096, PROT_NONE);
if (status != 0) { perror("mprotect"); exit(1); }
// protect second page
for (int i = 0; i <= 4096; i += 256) // test - should fail when i == 4096
{
printf("a[%d] = %u\n", i, a[i]);
}
return 0;
}
编译和测试:
$ gcc -Wall mprotect.c && ./a.out
a[0] = 0
a[256] = 0
a[512] = 0
a[768] = 0
a[1024] = 0
a[1280] = 0
a[1536] = 0
a[1792] = 0
a[2048] = 0
a[2304] = 0
a[2560] = 0
a[2816] = 0
a[3072] = 0
a[3328] = 0
a[3584] = 0
a[3840] = 0
Bus error: 10
$
请注意,当我们尝试读取 a[4096]
时产生了一个总线错误。
如果你在 gdb 下运行它,你会得到更多信息:
Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_PROTECTION_FAILURE at address: 0x0000000100803000
0x0000000100000eff in main () at mprotect.c:14
14 printf("a[%d] = %u\n", i, a[i]);
关于c++ - 强制页面边界段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25507277/