Memory Error and Leak Check:

In any code your write that dynamically allocates memory, you have 2 responsibilities regarding any block of memory allocated: (1) always preserve a pointer to the starting address for the block of memory so, (2) it can be freed when it is no longer needed.

It is imperative that you use a memory error checking program to insure you haven't written beyond/outside your allocated block of memory, attempted to read or base a jump on an unintitialized value and finally to confirm that you have freed all the memory you have allocated.

For Linux valgrind is the normal choice. There are many subtle ways to misuse a pointer or new block of memory. Using a memory error checker allows you to identify any problems and validate proper use of of the memory you allocate rather than finding a problem exists through a segfault. There are similar memory checkers for every platform. They are all simple to use, just run your program through it. The output of valgrind is easy to interpret, e.g.:

$ valgrind ./yourprogram arguments
==11777== Memcheck, a memory error detector
==11777== Copyright (C) 2002-2012, and GNU GPL'd, by Julian Seward et al.
==11777== Using Valgrind-3.8.1 and LibVEX; rerun with -h for copyright info
==11777== Command: /full/path/to/yourprogram arguments
==11777==

  your program output and any errors are listed here.

==11777==
==11777== HEAP SUMMARY:
==11777==     in use at exit: 0 bytes in 0 blocks
==11777==   total heap usage: 7 allocs, 7 frees, 35,240 bytes allocated
==11777==
==11777== All heap blocks were freed -- no leaks are possible
==11777==
==11777== For counts of detected and suppressed errors, rerun with: -v
==11777== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 2 from 2)

Always confirm under HEAP SUMMARY that All heap blocks were freed -- no leaks are possible and equally important ERROR SUMMARY: 0 errors from 0 contexts.