Electric Fence (Memory Debugger)
Table of Contents
1. Electric Fence(可检测内存非法访问)
Electric Fence is a debugger that uses virtual memory hardware to detect illegal memory accesses. It can detect two common programming bugs: software that overruns or underruns the boundaries of a malloc() memory allocation, and software that touches a memory allocation that has been released by free().
原理:
Electric Fence 利用底层硬件(CPU 提供的虚拟内存管理)提供的机制,对内存区域进行保护。它使用的 mprotect
系统调用,当被保护的内存被修改时,程序会立即 core 掉,通过检查 core 文件的 backtrace,就容易定位到问题代码。
1.1. 安装 Electric Fence
Electric Fence 安装方式如下(以 Ubuntu 14.04 为例):
sudo apt-get install electric-fence
2. Electric Fence 实例:检测内存越界
假设有下面程序(有内存越界访问 Bug):
#include <stdio.h> #include <malloc.h> int main(void) { int *a = (int*)malloc(2*sizeof(int)); /* 仅分配2个int的内存 */ int i; for (i=0;i<=5;i++) { a[i] = i; printf("%d\n", a[i]); } free(a); return 0; }
测试 1(不用 efence):
$ gcc -Wall -o test test.c && ./test 0 1 2 3 4 5
测试 2(使用 efence):
用 electric-fence,需要在编译的时候链接 efence 库。
$ gcc -Wall -o test test.c -lefence && ./test Electric Fence 2.2 Copyright (C) 1987-1999 Bruce Perens <bruce@perens.com> 0 1 zsh: segmentation fault (core dumped) ./test