Fixed some memory and resource leaks.
Fixed some common realloc mistakes, where a pointer was nulled but not freed upon failure.
Merge pull request #1 from DonChunior/master

Fixed some memory and resource leaks, as well as common realloc mistakes.