Debugging memory issues can be made much easier if you use Valgrind with gdb. To do this you need to ensure that the Valgrind gdbserver is enabled. You do this when Valgrind is started with the command below
$ valgrind --tool=memcheck --vgdb=yes --vgdb-error=0 <prog>
where <prog> is the path to the program you want to test e.g. ./test
You then need to open another terminal window and start gdb
$ gdb <prog>
You now need to tell gdb that you want to work with the remote target
(gdb) target remote | vgdb
You can now continue, and wait for gdb to break when Valgrind determines that there is a problem.
(gdb) c