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