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

Fixed some memory and resource leaks.
Fixed some common realloc mistakes, where a pointer was nulled but not freed upon failure.