Resolve multiple resource leaks and memory allocation problems

This pull request resolves several resource leaks and several memory allocation problems (correct usage of realloc). For a more detailed description please refer to the single commit messages.