Using electric fence for debugging memory leaks in Linux

Create a test program which has some memory leaks for understanding how to debug memory leaks with electric fence,

 $ vim efence.c 
#include <stdio.h>
#include <stdlib.h>
int main() {
        char *ptr = (char *) malloc(1024);
        ptr[0] = 0;
        /* Now write beyond the block */
        ptr[1024] = 0;

Now, we will need to install electric-fence package on ubuntu as,

 $ sudo apt-get install electric-fence
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following NEW packages will be installed:
0 upgraded, 1 newly installed, 0 to remove and 261 not upgraded.
Need to get 21.6 kB of archives.
After this operation, 88.1 kB of additional disk space will be used.
Get:1 trusty/universe electric-fence i386 2.2.4 [21.6 kB]
Fetched 21.6 kB in 1s (21.5 kB/s)
Selecting previously unselected package electric-fence.
(Reading database ... 209879 files and directories currently installed.)
Preparing to unpack .../electric-fence_2.2.4_i386.deb ...
Unpacking electric-fence (2.2.4) ...
Processing triggers for man-db ( ...
Setting up electric-fence (2.2.4) ...
Processing triggers for libc-bin (2.19-0ubuntu6.6) ...

Now, lets compile the program fr understanding without linking to electric fence,

 $ gcc -o efence efence.c 
 $ ./efence 

So, here when we execute the binary without linked with electric fence, it didn’t shown any error,

Now, lets link electric fence,

 $ gcc -o efence efence.c -lefence 
 $ ./efence

Electric Fence 2.2 Copyright (C) 1987-1999 Bruce Perens <>
Segmentation fault (core dumped)

Here, as we see the binary after executation return “Seg fault” which identifies the issue, now to identify exact code, we will use gdb as below,

 $ gcc -g -o efence efence.c -lefence 
 $ gdb efence 

GNU gdb (Ubuntu 7.7.1-0ubuntu5~14.04.2) 7.7.1
Copyright (C) 2014 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law. Type “show copying”
and “show warranty” for details.
This GDB was configured as “i686-linux-gnu”.
Type “show configuration” for configuration details.
For bug reporting instructions, please see:
Find the GDB manual and other documentation resources online at:
For help, type “help”.
Type “apropos word” to search for commands related to “word”…
Reading symbols from efence…done.

 (gdb) r 

Starting program: efence
[Thread debugging using libthread_db enabled]
Using host libthread_db library “/lib/i386-linux-gnu/”.

Electric Fence 2.2 Copyright (C) 1987-1999 Bruce Perens <>

Program received signal SIGSEGV, Segmentation fault.
0x08048596 in main () at efence.c:8
8 ptr[1024] = 0;


Leave a Comment